//#define LONGSTAMP 1

#ifndef LINUX
#include <direct.h>
#endif

#include "svn.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
//#include <cfortran.h>
//#include <packlib.h>
#include <errno.h>
#include <math.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <TROOT.h>
#include <TSystem.h>
#include <TFile.h>
//#include <TXMLFile.h>
#include <TColor.h>
#include <TApplication.h>
#include <TBrowser.h>
#include <TStyle.h>
#include <TGClient.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TLine.h>
#include <TPolyLine.h>
#include <TBox.h>
#include <TLegend.h>
//#include <TLatex.h>
//#include <TPaveText.h>
#include <TGraph.h>
#include <TRandom.h>
#include <TGButton.h>
#include <TGLabel.h>
#include <TKey.h>
#include <TObject.h>
#include <TDatime.h>
#include <TQObject.h>

#include <TRootEmbeddedCanvas.h>
#include <TGResourcePool.h>
#include "adcmana.h"

//#define _FILE_OFFSET_BITS 64

#define BSIZE 131072 //1024*128
//#define BSIZE 1000000 //1024*128
#define BOFFSET 1024
//#define BSIZE 1000000
#define DSIZE 4096
//#define THRESH 0.1 

//#define BKGR 8300

//Pixel_t yellow;

//int fp_id;
FILE* fp=0;
//FILE* fout=0;
//FILE* ftmp;

char fname[180]="";
char* rootname="";

//TDatime fTime;
char pr_name[180];
char maintitle[180];

char startdir[180];

const char* ng_name[] = {"gamma","neutrons","tail","other","pileup"};

unsigned short buf2[BSIZE+BOFFSET];
unsigned short *buf;
//unsigned short *sbuf[2];
int recd,idx,idnext;
int nevent,bad_events;
//int num_events;
//double devent;
int syncw,type,len,len2,dlen2;
int r_buf;

//event:
short int nbits; //ADC bits
short int nw; //samples per word = 2
short int nsamp; // number of samples recorded in the channel
short int nch; // channel number
short int id; // block id (=0,1,2)
int evcnt; // event count
int burstcnt; //burst count
int evprev; // previous event count
unsigned int tst=0; // temporary time stamp
int cnst=0; //temporary constant (64 bit timestamp)
int cnst_prev=0; //previous temporary constant (64 bit timestamp)
unsigned int tstamp=0; // time stamp
unsigned int pstamp=0; // time stamp of the previous event
unsigned int istamp=0; // number of tstamp overflows
Long64_t offset64; //istamp offset
Long64_t first64; //first timestamp (zero offset)
Long64_t tstamp64; //64-bit timestamp (corrected for overflows)
//Long64_t pstamp64; //64-bit timestamp of the previous event
Long64_t peak64; //64-bit peak time
Long64_t last_peak64[32]; //64-bit last peak time (from previous event)
Long64_t start64; 
//unsigned int tstart=0; // time start (from ch 15)

double tof,tof2,tof3,frame_tof,frame_tof2;
int png1 = -99;
unsigned int pstop1=0;

#define MAXRING 10

Long64_t t_ring[MAXRING];
Long64_t t_prev;
unsigned int nring;


//double pdstart; 
//double dstart; // tstart + istamp*1e9;
//unsigned int pstart=0; // previous time start (from ch 15)
//unsigned int gstart=0; // time start (from ch 6 - pulser 100 hz)
//unsigned int istart=999999; // number of starts (every 3rd)
//unsigned int tstop[32]; // time stop
//unsigned int constant; //
unsigned short data[DSIZE];
int mult=0;
int chan[32];
bool new_event=false;
bool beam_on=false;
unsigned short Event[32][DSIZE];
double bEvent[32][DSIZE]; // background subtracted
double sEvent[32][DSIZE]; // smoothed
//double sDeriv[32][DSIZE]; // derivative smoothed
double xgr[DSIZE]; // x coordinate for graph

int findbeam=0;
int checkpoint=0;

//TSet *settings;

/*
double pthresh[32][2];
double pborder[2];
double pdelta[32][2];
double tdc_bins[2];
double starts_thr[2];
double beam[2];
double wgam[2],wneu[2],wtail[2];
//double period[2];
int b_osc,b_leg;
*/

int npeaks[32];
int peaks[32][DSIZE];
int peaks1[32][DSIZE];
int peaks2[32][DSIZE];
int peaks0[32][DSIZE];
int peak_flag[32][DSIZE]; 
// 0 -undetermined; 2 - gamma; 3 - neutron; 4 - tail; 5 - unknown; 6 - NIM;
// 11 - bad "left"; 12 - bad "right"; 13 - true pileup; 14 - false pileup


double evmax[32];

double sum[32][DSIZE];
double mean[32][DSIZE];
double rms[32][DSIZE];

//double sdata[DSIZE];

//#define MAXARRAY 1000000
//int f_long_t[32][MAXARRAY];

TH1F* hmak;
TH1F* hmon;

TH1F *hsum_ng[MAX_P]; // 0-gamma; 1-neutron; 2-tail; 3-unknown
TH1F *htdc_ng[MAX_P];
TH1F *htdc_a_ng[MAX_P];
TH1F *hrms_ng[MAX_P];


TH1F *hsum[32];
TH1F *hmax[32];
TH1F *hrms;
TH2F *hsumrms;
TH1F *hstart;
TH1F *htdc[32]; // tof relative to "each" nuclotron pulse
                   // 0-all; 1-gamma; 2-n
TH1F *htdc_a[32]; //absolute tof (start=0)
                   // 0-all; 1-gamma; 2-n

#ifdef ROMASH
TH1F *htof_m[24];
int mult_gam;
#endif

TH1F *htdc_frame[32]; //absolute tof (start=0) for frames

TH1F *hdeltat[4]; // time between neighboring pulses 
                  // 0: g-g; 1: g-n; 2: n-g; 3: n-n

TH1F *hsync;

//TH1F *spec[6];

//char hstnam[100];

MyMainFrame *myM;

/*
#define PAWC_SIZE 50000000
typedef struct { double PAW[PAWC_SIZE]; } PAWC_DEF;
#define PAWC COMMON_BLOCK(PAWC,pawc)
COMMON_BLOCK_DEF(PAWC_DEF,PAWC);
PAWC_DEF PAWC;
*/

//int channels[32];


Toptions opt;
int *opt_id[MXNUM];
//const char *opt_label[MXNUM];
//const char *opt_tip[MXNUM];

void reset();
void new_hist();
void set_hist_attr();
void newfile();
void clear_hist();
void readinit(const char* fname);
void saveinit(const char* fname);
//void saveinit2();
void smooth(int n, int i);
int analyze();
void swap_words(unsigned short* buf, int size);
int nextevent();
//int nextidx(int n);
int searchsync();
void dumpbuf();
void dumpevent();
int readbuf();
short int bits(int n, int i1, int i2);

void saveroot(char *name);
void allevents();
void example();

using namespace std;


Toptions::Toptions() {

  //cout << "toptions" << endl;
  for (int i=0;i<MAX_CH;i++) {
    channels[i]=ch_off;
    //cout << i << " toptions " << channels[i] << endl;
  }
  //www[0]=1.0;
  //www[1]=5.0;

  gam_thresh = 20;
  gam_elim1=20;
  gam_elim2=9999;
  gam_border1=-5;
  gam_border2=100;
  gam_pile1=20;
  gam_pile2=120;

  ng_thresh = 15;
  ng_elim1=5;
  ng_elim2=9999;
  ng_border1=-7;
  ng_border2=8;
  ng_pile=20;

  nim_thresh1=500;
  nim_thresh2=50;

  tdc_bins1=1000;
  tdc_bins2=1000;

  starts_thr1=10000;
  starts_thr2=6;

  beam1=0.0;
  beam2=0.0;

  wgam1=2;
  wgam2=3;

  wneu1=3;
  wneu2=4;

  wtail1=4;
  wtail2=5;

  gcut[0]=NULL;
  gcut[1]=NULL;
  gcut[2]=NULL;

  num_events=100000;

  b_gcut=false;

  b_osc=false;
  b_leg=false;
  //for (int jj=0;jj<6;jj++) {
  b_logy=false;
    //}
  b_time=false;

  nsmoo=2;
  psd_ch=0;
  start_ch=0;

  draw_opt=M_DEMON;

  /*
  for (int i=0;i<30;i++) {
    opt_label[i]="";
    opt_tip[i]="";
  }
  */

  for (int i=0;i<32;i++) {
    sprintf(opt.chname[i],"ch%02d",i);    
    opt.color[i]=0;
    opt.channels[i]=ch_off;
    //sprintf(chname[i],"ch%0d",i);
  }

  sprintf(opt.chname[0],"demon");
  sprintf(opt.chname[2],"isomer");
  sprintf(opt.chname[6],"pulser");
  sprintf(opt.chname[8],"monitor1");
  sprintf(opt.chname[12],"stilbene");
  //sprintf(opt.chname[12],"monitor2");
  sprintf(opt.chname[14],"start");

  channels[0]=ch_ng;
  channels[2]=ch_nim;
  channels[6]=ch_nim;
  channels[8]=ch_nim;
  channels[12]=ch_ng;
  channels[14]=ch_nim;

  color[0]=1;
  color[2]=1;
  color[6]=1;
  color[8]=1;
  color[12]=1;
  color[14]=1;

  vmon[0]= 8;
  vmon[1]= 10;
  vmon[2]=-0.1;
  vmon[3]= 0.6;
  vmon[4]= 6;

  Tstart=0;
  Tstop=0;

  Ecalibr[0]=0.0;
  Ecalibr[1]=1.0;

  //printf("opt: %f\n", *(double*) opt_id[9]);

}

//Toptions::~Toptions() {
//}

//void Toptions::Read(char* filename) {
//}

void SplitFilename (string str, char *folder, char *name)
{
  size_t found;
  //cout << "Splitting: " << str << endl;
  found=str.find_last_of("/\\");
  //cout << " folder: " << str.substr(0,found) << endl;
  //cout << " file: " << str.substr(found+1) << endl;
  //printf("%s %s\n",str.substr(0,found+1).c_str(),str.substr(found+1).c_str());

  strcpy(folder,str.substr(0,found+1).c_str());
  strcpy(name,str.substr(found+1).c_str());

}

void SplitFilename (string str, char *folder, char *name, char* ext)
{

  SplitFilename(str, folder, name);
  string fname(name);
  size_t found = fname.find_last_of(".");
  strcpy(name,fname.substr(0,found).c_str());
  strcpy(ext,fname.substr(found+1).c_str());
}

int main(int argc, char **argv)
{

  int i,j,len;
  char s_name[200], dir[100], name[100], ext[100];
  char* parname = (char*) "init.par";

  bool batch=false;

  /*
  if (argc < 2) {
    printf("usage: %s infile\n",argv[0]);
    exit(-1);
  }
  */

  #ifdef LINUX
  getcwd(startdir,100);
  #else
  _getcwd(startdir,100);
  #endif
  //cout << "startdir: " << startdir << endl;

  for (i=0;i<DSIZE;i++) {
    xgr[i]=i;
  }

  strcpy(pr_name,argv[0]);

  strcat(pr_name," v.");
  strcat(pr_name,SVNVERSION);

  strcpy(maintitle,pr_name);

  //strcpy(fname," ");
  if (argc > 1) {
    strcpy(fname,argv[1]);
    printf("%s\n",fname);
    strcat(maintitle," ");
    strcat(maintitle,fname);
  }

  if (argc > 2) {
    if (!strcmp(argv[2],"run")) {
      batch=true;
      //parname= (char*) "init.par";
    }
    else {
      parname=argv[2];
    }
  }

  readinit(parname);
  reset();
  newfile();

  if (argc > 3) {
    if (!strcmp(argv[3],"run")) {
      batch=true;
    }
  }

  if (batch) {
    //opt.num_events=0;
    allevents();

    SplitFilename (string(fname),dir,name,ext);
    strcat(dir,"save/");
#ifdef LINUX
    mkdir(dir,0755);
#else
    _mkdir(dir);
#endif
    strcpy(s_name,dir);
    strcat(s_name,name);
    strcat(s_name,".root");
    cout << s_name << endl;
    saveroot(s_name);
    return 0;
  }

  TApplication theApp("App",&argc,argv);
  example();
  //gClient->GetColorByName("yellow", yellow);
  theApp.Run();
  //return 0;

  //do {
  //;
  //} while (nextevent()==0);


  //fclose(fout);
  fclose(fp);

  //printf("%d buffers\n",nbuf);
  printf("%d bytes\n",recd*2);
  printf("%d events\n",nevent);
  printf("%d bad events\n",bad_events);

  //HRPUT(0,(char*)"spectra.hbook",(char*)" ");

  //memcpy(buf2,buf[0],BSIZE);

}

void new_hist() {

  int i,j;

  char title[100];

  char nam[100];

  sprintf(nam,"width_energy");
  if (hsumrms!=NULL) {
    hsumrms->Reset();
    hsumrms->SetNameTitle(nam,nam);
  }
  else {
    hsumrms=new TH2F(nam,nam,800,0.,8.,800,0.,800.);
  }

  for (j=0;j<4;j++) {
    sprintf(nam,"deltat_%d",j);
    if (hdeltat[j]!=NULL) hdeltat[j]->Delete();
    hdeltat[j]=new TH1F(nam,nam,1000,0.,1000.);
    hdeltat[j]->GetXaxis()->SetNdivisions(505);
  }

  for (j=0;j<MAX_P;j++) {
    //printf("%s\n",ng_name[j]);
    sprintf(nam,"energy_%s",ng_name[j]);
    sprintf(title,"%s",ng_name[j]);
    if (hsum_ng[j]!=NULL) hsum_ng[j]->Delete();
    hsum_ng[j]=new TH1F(nam,title,4000,0.,1000.);

    sprintf(nam,"time_%s",ng_name[j]);
    //sprintf(nam,"time_ng_%02d",j);
    if (htdc_ng[j] != NULL) htdc_ng[j]->Delete();
    htdc_ng[j]=new TH1F(nam,title,25*opt.tdc_bins2,0.,25.);

    sprintf(nam,"long_time_%s",ng_name[j]);
    //sprintf(nam,"long_time_ng_%02d",j);
    if (htdc_a_ng[j] != NULL) htdc_a_ng[j]->Delete();
    htdc_a_ng[j]=new TH1F(nam,title,200*opt.tdc_bins1,0.,200.);
    htdc_a_ng[j]->SetBit(TH1::kCanRebin);

    sprintf(nam,"width_%s",ng_name[j]);
    if (hrms_ng[j] != NULL) hrms_ng[j]->Delete();
    hrms_ng[j]=new TH1F(nam,title,800,0.,8.);

  }

  sprintf(nam,"width");
  if (hrms != NULL) hrms->Delete();
  hrms=new TH1F(nam,nam,800,0.,8.);

  for (i=0;i<32;i++) {
    sprintf(nam,"energy_%s",opt.chname[i]);
    sprintf(title,"%s",opt.chname[i]);
    //printf("%d %s %s\n",i,nam,opt.chname[i]);
    if (hsum[i]!=NULL) hsum[i]->Delete();
    hsum[i]=new TH1F(nam,title,4000,0.,1000.);

    sprintf(nam,"max_%s",opt.chname[i]);
    sprintf(title,"%s",opt.chname[i]);
    //printf("%d %s %s\n",i,nam,opt.chname[i]);
    if (hmax[i]!=NULL) hmax[i]->Delete();
    hmax[i]=new TH1F(nam,title,30000,8000.,38000.);

    sprintf(nam,"time_%s",opt.chname[i]);
    if (htdc[i] != NULL) htdc[i]->Delete();
    htdc[i]=new TH1F(nam,title,25*opt.tdc_bins2,0.,25.);

    sprintf(nam,"long_time_%s",opt.chname[i]);
    if (htdc_a[i] != NULL) htdc_a[i]->Delete();
    htdc_a[i]=new TH1F(nam,title,200*opt.tdc_bins1,0.,200.);
    htdc_a[i]->SetBit(TH1::kCanRebin);

    sprintf(nam,"frame_time_%s",opt.chname[i]);
    sprintf(title,"frames_%s",opt.chname[i]);
    if (htdc_frame[i] != NULL) htdc_frame[i]->Delete();
    htdc_frame[i]=new TH1F(nam,title,200*opt.tdc_bins1,0.,200.);
    htdc_frame[i]->SetBit(TH1::kCanRebin);

  }

#ifdef ROMASH
  for (i=0;i<24;i++) {
    sprintf(nam,"tof_m_%s",opt.chname[i]);
    sprintf(title,"tof_m_%s",opt.chname[i]);
    if (htof_m[i] != NULL) htof_m[i]->Delete();
    htof_m[i]=new TH1F(nam,title,500000,0.,100000.);
  }
#endif

  if (hsync != NULL) hsync->Delete();
  hsync=new TH1F("hsync","hsync",20000,0.,20.);

  float xbins[3]={0,1,2};

  if (hmak != NULL) hmak->Delete();
  hmak=new TH1F("hmak","hmak",2,xbins);

  if (hmon != NULL) hmon->Delete();
  hmon=new TH1F("hmon","hmon",2,xbins);

  hmak->SetLineColor(2);
  hmak->SetFillColor(2);
  hmak->SetMinimum(0);
  hmak->SetBarWidth(0.2);
  hmak->SetBarOffset(0.0);

  hmon->SetLineColor(3);
  hmon->SetFillColor(3);
  hmon->SetMinimum(0);
  hmon->SetBarWidth(0.2);
  hmon->SetBarOffset(0.0);

}

void set_hist_attr() {

  int i,j;

  for (j=0;j<MAX_P;j++) {
    hsum_ng[j]->SetLineColor(opt.color[MAX_CH+j+1]);
    hsum_ng[j]->GetXaxis()->SetNdivisions(505);

    htdc_ng[j]->SetLineColor(opt.color[MAX_CH+j+1]);
    htdc_ng[j]->GetXaxis()->SetNdivisions(505);

    htdc_a_ng[j]->SetLineColor(opt.color[MAX_CH+j+1]);
    htdc_a_ng[j]->GetXaxis()->SetNdivisions(505);
    //htdc_a_ng[j]->GetXaxis()->SetTimeDisplay(1);

    hrms_ng[j]->SetLineColor(opt.color[MAX_CH+j+1]);
  }

  for (i=0;i<32;i++) {
    hsum[i]->SetLineColor(opt.color[i]);
    hsum[i]->GetXaxis()->SetNdivisions(505);

    hmax[i]->SetLineColor(opt.color[i]);
    hmax[i]->GetXaxis()->SetNdivisions(505);

    htdc[i]->SetLineColor(opt.color[i]);
    htdc[i]->GetXaxis()->SetNdivisions(505);

    htdc_a[i]->SetLineColor(opt.color[i]);
    htdc_a[i]->GetXaxis()->SetNdivisions(505);
    htdc_a[i]->GetXaxis()->SetTicks("+-");
    //htdc_a[i]->GetXaxis()->SetTimeDisplay(1);

    htdc_frame[i]->SetLineColor(2);
    htdc_frame[i]->GetXaxis()->SetNdivisions(505);
    //htdc_frame[i]->GetXaxis()->SetTimeDisplay(1);

  }

}

/*
void set_time_offset() {

  int i,j;

  for (j=0;j<MAX_P;j++) {
    htdc_a_ng[j]->GetXaxis()->SetTimeDisplay(1);
  }

  for (i=0;i<32;i++) {
    htdc_a[i]->GetXaxis()->SetTimeDisplay(1);
    htdc_frame[i]->GetXaxis()->SetTimeDisplay(1);
  }

}
*/
void saveroot(char *name) {

  TFile * tf = new TFile(name,"RECREATE");

  //int nn=0;
  int col;

  //hrms->Write();
  //tf->Close();
  //return;

  gROOT->cd();

  TIter next(gDirectory->GetList());

  tf->cd();

  TH1F *h;
  TH2F *h2;
  TObject* obj;
  while ( obj= (TObject*)next() ) {
    if (obj->InheritsFrom(TH2::Class())) {
      h2=(TH2F*) obj;
      //h2->Print();
      if (h2->GetEntries() > 0) {
	//printf("saveroot2: %s\n",h2->GetName());
	h2->Write();
      }
    }
    else if (obj->InheritsFrom(TH1::Class())) {
      h=(TH1F*) obj;
      //h->Print();
      if (h->GetEntries() > 0) {
	col=h->GetLineColor();
	//printf("saveroot: %d %s\n",col,h->GetName());
	if (col==0) {
	  h->SetLineColor(50);
	}
	//tf->WriteTObject(obj);
	h->Write();
	h->SetLineColor(col);
      }
    }
  }

  opt.Nevt=nevent;
  opt.Tof=tof;
  opt.Write();

  cout << "Histograms and parameters are saved in file: " << name << endl;

  tf->Close();
}

void readroot(char *name) {

  char nam[100];

  //cout << opt.channels[0] << endl;

  gROOT->cd();
  TList *list = gDirectory->GetList();

  //list->ls();

  TFile *tf = new TFile(name,"READ");

  TIter next(tf->GetListOfKeys());

  TKey *key;
  TObject *obj;
  TH1* obj2;
  while ((key = (TKey*)next())) {
    //key->Print();

    //cout << key->GetClassName() << endl;
    if (strcmp(key->GetClassName(),"Toptions")) {
      obj=key->ReadObj();
      if (obj->InheritsFrom(TH1::Class())) {
	//obj->Print();

	//obj->Print();
	obj2 = (TH1*) list->FindObject(obj->GetName());
	TDirectory* dir = obj2->GetDirectory();

	obj->Copy(*obj2);
	obj->Delete();
	obj2->SetDirectory(dir);
      }
    }

  }

  //opt.Read("Toptions");

  tf->Close();

  //strcpy(maintitle,pr_name);
  //strcat(maintitle," ");
  //strcat(maintitle,name);

  //cout << opt.channels[0] << endl;
}

void clear_hist() {

  //memset(f_long_t,0,sizeof(f_long_t));

  TIter next(gDirectory->GetList());

  TH1 *h;
  //TH2F *h2;
  TObject* obj;
  while ( obj= (TObject*)next() ) {
    if (obj->InheritsFrom(TH1::Class())) {
      h=(TH1*) obj;
      h->Reset();
    }
  }

}

void reset() {
  int i,j;

  new_hist();
  set_hist_attr();

  buf=buf2+1024;

  beam_on=false;
  //nbuf=0;
  recd=0;
  nevent=-1;
  evprev=-9;
  //  devent=0;
  bad_events=0;
  idx=0;
  istamp=0;
  tstamp=0;
  pstamp=0;
  cnst_prev=0;

  tof=0;
  //opt.Tof=0;
  new_event=false;
  //dstart=-999;
  start64=(Long64_t) (-100*1e8);
  first64=0;
  offset64=0;
  //pdstart=-999;
  nring=0;
  memset(t_ring,0,sizeof(t_ring));

  for (i=0;i<32;i++)
    last_peak64[i]=0;

  //printf("reset: %d %d\n",tstamp,pstamp);
}

void newfile()
{
  if (fp != 0) {
    fclose(fp);
  }
  //printf("file %s\n",fname);
  fp=fopen(fname,"rb");
  //fout=fopen("out.dat","w");

  Long_t id;
  Long64_t size;
  Long_t flags;
  Long_t modtime;

  int ires=gSystem->GetPathInfo(fname, &id, &size, &flags, &modtime);
  //printf("Finfo: %d %d %d %d %d\n",ires, id, size, flags, modtime);
  //cout << "finfo: " << ires << " " << modtime << endl;
  opt.F_stop.Set(modtime);
  opt.F_stop.Print();
  gStyle->SetTimeOffset(opt.F_start.Convert(false));

  /*
#ifdef LINUX
  struct stat attrib;			// create a file attribute structure
  stat(fname, &attrib);		// get the attributes of afile.txt
  //cout << attrib.st_mtime << endl;
  //TDatime fTime;
  opt.F_stop.Set(attrib.st_mtime);
  //opt.F_stop.Print();
  gStyle->SetTimeOffset(opt.F_start.Convert(false));
#else

#endif
  */

  if (fp==0) {
    printf("Can't open file %s\n",fname);
    //printf("fp: %d %d\n",fp,errno);
    //exit(-1);
  }

  if (readbuf()) {
    return;
  }

  nextevent();

  /*
  cout << "sdfsdfsdf" << endl;

  do {
    if (!searchsync()) {
      printf("Can't find events in file %s\n",fname);
      return;
    }
    cout << "buf[idx]: " << idx << " " << hex << buf[idx] << endl;
  } while (buf[idx]!=0x100);
  */

  //swap_words(buf,BSIZE);
}

void readinit(const char* parname)
{

  FILE* finit;
  int i;
  char ss[7];

  TFile *f2 = new TFile(parname,"READ");

  opt.Read("Toptions");

  f2->Close();
  delete f2;


}

void saveinit(const char* parname)
{

  FILE* finit;
  int i;
  char ss[7];


  //char ttt[100];
  //getcwd(ttt,100);
  //cout << ttt << endl;
  
  #ifdef LINUX
  chdir(startdir);
  #else
  _chdir(startdir);
  #endif

  TFile *f2 = new TFile(parname,"RECREATE");

  opt.Write();

  //TNamed2 *tn = new TNamed2("Name1","Title2");
  //tn->Dump();
  //tn->Write();
  //delete tn;

  f2->Close();
  delete f2;

}

void smooth(int n, int i)
{
  int j,j1,k,ll;

  evmax[i]=0;
  memset(sEvent[i],0,nsamp*sizeof(double));

  for (j=0;j<nsamp;j++) {
    if (Event[i][j]>evmax[i]) {
      evmax[i]=Event[i][j];
    }
    ll=0;
    for (j1=-n;j1<=n;j1++) {
      k=j+j1;
      if (k>=0 && k<nsamp) {
	sEvent[i][j]+=Event[i][k];
	ll++;
      }
    }
    sEvent[i][j]/=ll;

    //if (j>0) {
    //sDeriv[i][j]=sEvent[i][j]-sEvent[i][j-1];
    //}
    //sEvent[i][j]-=bkgr[i];
  }

  /*
  for (j=0;j<nsamp-1;j++) {
    bEvent[i][j]=sEvent[i][j+1]-sEvent[i][j];
  }
  */
}

/*
int subtr_bkgr(int cmax, int i) //subtract background
{
  int j;
  double bkgr=0;

  //bkgr=0;
  for (j=0;j<cmax;j++) {
    bkgr+=Event[i][j];
  }
  bkgr=bkgr/cmax;
  //printf("%f\n",bkgr);

  for (j=0;j<nsamp;j++) {
    bEvent[i][j]=Event[i][j]-bkgr;
    //printf("%d %d %d %f %d %f\n",i,j,cmax,bkgr,Event[i][j],bEvent[i][j]);
  }

  return 0;

}
*/

void fill_nim(int ch) {

  tof  = (peak64-first64)*1e-8;
  tof2 = (peak64-start64)*1e-8;
  tof3=tof2*100;
  htdc_a[ch]->Fill(tof);


  //fill_long(tof,f_long_t[ch]);

  if ((opt.beam2<=0) || 
      (beam_on && tof3>=opt.beam1 && tof3 < opt.beam2)) {

    if (beam_on) {
      htdc[ch]->Fill(tof2);
    }
  }

}

void nim_peak(int ch, int j) {

  //static Long64_t oldstart;

  peak64=tstamp64+j;
  if (peak64 > last_peak64[ch]) { //reject double counting
    if (opt.starts_thr2==0 && ch == opt.start_ch && tof2 > opt.starts_thr2) {

      double dlt = (peak64-start64)*1e-8;
      hsync->Fill(dlt);

      //cout << "NIMStart64: " << dlt << " " << peak64*1e-8 << endl;

      start64=peak64;

      if (!beam_on)
	beam_on=true;
    }
    peaks[ch][npeaks[ch]++]=j;
    //printf("nim_peak: %d %d %d\n",ch,npeaks[ch],peaks[ch][npeaks[ch]-1]);
    fill_nim(ch);
    last_peak64[ch]=peak64;
  }

}

void findpeaks_nim(int ch, int n2, unsigned short* dat)
// analyse the pulse, find peaks
// peaks[0] .. peaks[npk-1] - peaks
{
  int j;

  //printf("thresh: %f\n",thresh);

  npeaks[ch]=0;
  //*(peaks)=-10;
  
  for (j=2;j<n2;j++) {
    if ( *(dat+j) - *(dat+j-1) >= opt.nim_thresh1      && 
	 *(dat+j-1) - *(dat+j-2) < opt.nim_thresh1) {
      nim_peak(ch,j);
      j+=opt.nim_thresh2; // skip nim dead time
    }
    //printf("nim: %d %d\n",j,npeaks[ch]);
  }

  //*(peaks+*npk+1)=n2;
  
  //return 0;

}

void peakana_ng(int ch, int n2, double* dat)
{
  int i,j;

  int x1,x2;
  double y1,y2,bkg,bkg2;

  double asum2,sum2,mean2,rms2;
  //double max;


  //first analyse all peaks for pile-up, then fill (in the next .for. loop)
  for (i=0;i<npeaks[ch];i++) {
    peak_flag[ch][i]=0;
    if (peaks1[ch][i]<0) { // too close to the left border
      peak_flag[ch][i]=11;
    }
    //else if (peaks2[ch][i]>n2-10) { // too close to the right border
    //peak_flag[ch][i]=12;
    //}
    else {
      if (i>0) {// this is at least second peak in the sample -> check for pileups
	if (peaks[ch][i]-peaks[ch][i-1] < opt.ng_pile) {
	  //real pileup: both peaks are bad
	  peak_flag[ch][i]=13;
	  peak_flag[ch][i-1]=13;
	  //cout << "pileup" << endl;
	}
      }
    }
  } // for (i

  for (i=0;i<npeaks[ch];i++) {
    //cout << peak_flag[ch][i] << endl;

    tof = tstamp64+peaks[ch][i];
    tof2 = tstamp64+peaks[ch][i]-start64;
    tof  = (tof-first64)*1e-8;
    //tof=tof/1e8;
    tof2=tof2*1e-8;
    tof3=tof2*100;

    //cout << peak_flag[ch][i] << endl;

    if (peak_flag[ch][i] == 13) {
      if (ch==opt.psd_ch) {
	htdc_a_ng[4]->Fill(tof);
	if (beam_on) {
	  htdc_ng[4]->Fill(tof2);
	}
      }
    }
    else if (peak_flag[ch][i] == 0) {
      x1=peaks1[ch][i];
      x2=peaks2[ch][i];

      y1= *(dat+x1);
      y2= *(dat+x2);

      bkg2=(y2+y1)/2;

      //bkg2=BKGR;

      /*
      bkg2=0;
      for (j=0;j<5;j++) {
	bkg2+=*(dat+x1-j);
      }
      bkg2/=5;
      */

      sum[ch][i]=0;
      asum2=0;
      mean2=0;
      rms2=0;

      for (j=x1;j<x2;j++) {
	double w=*(dat+j)-bkg2;
	double aw=fabs(w);
	sum[ch][i]+=w;
	asum2 += aw;
	mean2 += aw*j;
	rms2 += aw*j*j;
      }

      mean2=mean2/asum2;
      rms[ch][i]=sqrt(rms2/asum2-mean2*mean2);
      rms2=rms[ch][i];//*100.0;
      sum2=(sum[ch][i]/100.0)*opt.Ecalibr[1]+opt.Ecalibr[0];

      //printf("rms2: %d %d %f %f %f %f %f %f\n",ch,i,bkg2,sum[ch][i],asum2,mean2,rms2,rms[ch][i]);
      
      int f_ng=3;

      if (opt.b_gcut) { //use 2d Gcuts
	//if (opt.gcut[0]!=NULL && opt.gcut[1]!=NULL) {
	  if (opt.gcut[0]!=NULL && 
	      opt.gcut[0]->IsInside(rms[ch][i],sum2)) { //gamma
	    peak_flag[ch][i]=2;
	    f_ng=0;
	  }
	  else if (opt.gcut[1]!=NULL && 
		   opt.gcut[1]->IsInside(rms[ch][i],sum2)) { //neutron
	    peak_flag[ch][i]=3;
	    f_ng=1;
	  }
	  else if (opt.gcut[2]!=NULL && 
		   opt.gcut[2]->IsInside(rms[ch][i],sum2)) { //tail
	    peak_flag[ch][i]=4;
	    f_ng=2;
	  }
	  else { // other
	    peak_flag[ch][i]=5;
	  }
	  //}
      }
      else { // use usual 1d borders
	if (rms2 >=opt.wgam1 && rms2 < opt.wgam2) { // gamma
	  peak_flag[ch][i]=2;
	  f_ng=0;
	}
	else if (rms2 >=opt.wneu1 && rms2 < opt.wneu2) { // neutron
	  peak_flag[ch][i]=3;
	  f_ng=1;
	}
	else if (rms2 >=opt.wtail1 && rms2 < opt.wtail2) { // tail
	  peak_flag[ch][i]=4;
	  f_ng=2;
	}
	else { // other
	  peak_flag[ch][i]=5;
	}
      }

      //printf("tof: %f %f %f %f\n",tof,tof2,double (tstamp64), double(start64));

      //if (ch==opt.psd_ch) {
      //hsumrms->Fill(rms[ch][i],sum2);
      //}

	htdc_a[ch]->Fill(tof);
	
	if (beam_on) {
	  htdc[ch]->Fill(tof2);
	}
	  //}

	if (sum2>=opt.ng_elim1 && sum2<opt.ng_elim2 ) {

	//fill_long(tof,f_long_t[ch]);
	if (ch==opt.psd_ch) {
	  htdc_a_ng[f_ng]->Fill(tof);
	}

	if ((opt.beam2<=0) || 
	    (beam_on && tof3>=opt.beam1 && tof3 < opt.beam2)) {

	  //htdc[ch]->Fill(tof2);
	  if (ch==opt.psd_ch) {
	    if (beam_on) {
	      htdc_ng[f_ng]->Fill(tof2);
	    }
	  }

	  hmax[ch]->Fill(evmax[i]);
	  //if (evmax[i]>14000) {
	  //checkpoint=1;
	  //}
	  //if (sum2>500) {
	  //checkpoint=1;
	  //}
	  //hmax[ch]->Fill(max);
	  hsum[ch]->Fill(sum2);
	  if (ch==opt.psd_ch) {
	    hrms->Fill(rms[ch][i]);
	    hrms_ng[f_ng]->Fill(rms[ch][i]);
	    hsumrms->Fill(rms[ch][i],sum2);
	    hsum_ng[f_ng]->Fill(sum2);

	    //if (rms[ch][i]>3 && peak_flag[ch][i]<10) {
	    //checkpoint = 1;
	    //}


	  }
	}
      } //if (sum[ch][i]>=opt.gam_thresh[1])
    } // if peak_flag=0

  } //for i

}

void findpeaks_ng(int ch, int n2, double* dat)
// analyse the pulse, find peaks
// peaks[0] .. peaks[npk-1] - peaks
{
  int j,i;
  double dif[DSIZE];

  npeaks[ch]=0;
  int nn=0;
  int in_peak=0;

  double mean;
  double sum;
  double rms2;

  //if (nevent>2000000) {
  //cout << nevent << " " << last_peak64[ch] << " " << tstamp64 << " ";
  //}

  dif[0]=0.0;
  for (j=1;j<n2;j++) {
    dif[j]=*(dat+j) - *(dat+j-1);
    if (in_peak==1) {//find peak maximum (=diff zero crossing)
      if (dif[j]<0) {
	if (j-1+opt.ng_border2>n2-opt.ng_pile/2) {// too close to the right border
	  j=n2;
	  in_peak=0;
	}
	else { // good peak
	  peaks[ch][nn]=j-1;
	  peaks1[ch][nn]=j-1+opt.ng_border1;
	  peaks2[ch][nn]=j-1+opt.ng_border2;
	  in_peak=2;
	}
	//rms2=0;
	//mean=0;
	//sum=0;
      }
    }
    else if (in_peak==2) {//right border, end of the peak, start new peak
      if (dif[j]>=0) {
	j--;
	//peaks2[ch][nn]=j;
	in_peak=0;
	last_peak64[ch]=peak64;
	nn++;
	npeaks[ch]=nn;
      }
      //else { // still inside the peak...
	//double w=-dif[j];//*(dat+j-1)-*(dat+j);
	//sum += w;
	//mean += w*j;
	//rms2 += w*j*j;
      //}
    }
    else { //in_peak==0
      if ( dif[j] >= opt.ng_thresh &&
	   dif[j-1] < opt.ng_thresh) {
	peak64=tstamp64+j;

	//if (nevent>2000000) {
	//cout << peak64 << " ";
	//}

	//if (nevent > 30000) {
	//printf("gam1: %d %d %d %d %d %f %f\n",nevent,ch,npeaks[ch],
	//i,j,double(peak64),double(last_peak64[ch]));
	//}

	if (peak64 > last_peak64[ch]+3) { //reject double counting
	  // here we're already inside the peak
	  peaks[ch][nn]=0;
	  peaks1[ch][nn]=0;
	  peaks2[ch][nn]=0;
	  rms[ch][nn]=0;
	  //left border of the peak
	  /* skip it..., just defined by the corresponding parameter
	  for (i=j-1;i>0;i--) {
	    //printf("gam1: %d %d %f\n",j,i,dif[i]);
	    if (dif[i]<=0) {
	      peaks1[ch][nn]=i;
	      break;
	    }
	  }
	  */
	  //peaks[ch][nn]=j;
	  in_peak=1;
	} // reject double counting
	else {
	  /*
	  cout << "double: " << nevent << " " << peak64 << " "
	       << ch << " "
	       << last_peak64[ch] << endl;
	  */
	  j+=10;
	}
	//gam_peak(ch,j);
      
	//printf("gam2: %d %d %f\n",j,i,dif[j]);
      } // if dif...
    } // else...
  } // for j

  //if (nevent>2000000) {
  //cout << endl;
  //}

  peakana_ng(ch,n2,dat);
  //peaks1[ch][0]-=2;
  //peakana_ng(ch,n2,dat);

  //if (nevent > 30000) {
  //printf("gam2: %d %d\n",ch,npeaks[ch]);
  //}

}

void peakana_gam(int ch, int n2, double* dat)
{
  int i,j;

  int x1,x2;
  double y1,y2,bkg;

  for (i=0;i<npeaks[ch];i++) {
    if (peak_flag[ch][i]==2) {
      x1=peaks1[ch][i];
      x2=peaks2[ch][i];
      y1= *(dat+x1);
      y2= *(dat+x2);

      bkg=(y2+y1)/2*(x2-x1);

      sum[ch][i]=0;
      //max=0;
      for (j=x1;j<x2;j++) {
	sum[ch][i]+=*(dat+j);
	//if (*(dat+j) > max)
	//max=*(dat+j);
      }

      sum[ch][i]-=bkg;
      //printf("ana: %d %f %f\n",x2-x1,(y2+y1)/2,bkg);

      //cout << sum[ch][i] << endl;
      /*
      if (ch==18) {
	printf("gams: %d %d %f\n",ch,i,sum[ch][i]);
      }
      */
      hmax[ch]->Fill(evmax[i]);
      //hmax[ch]->Fill(max);
      hsum[ch]->Fill(sum[ch][i]/100.0);
      tof = tstamp64+peaks[ch][i];
      tof2 = tstamp64+peaks[ch][i]-start64;
      tof  = (tof-first64)*1e-8;
      //tof=tof/1e8;
      tof2=tof2*1e-8;
      tof3=tof2*100;


      //fill_long(tof,f_long_t[ch]);
      htdc_a[ch]->Fill(tof);
      if ((opt.beam2<=0) || 
	  (beam_on && tof3>=opt.beam1 && tof3 < opt.beam2)) {

	if (beam_on) {
	  htdc[ch]->Fill(tof2);
	}
      }

    }
    //peaks[ch][i]
  }

}

void findpeaks_gam(int ch, int n2, double* dat)
// analyse the pulse, find peaks
// peaks[0] .. peaks[npk-1] - peaks
{
  int j,i;
  double dif[DSIZE];

  //fwrite(dat,n2*sizeof(double),1,fout);
  //for (j=0;j<n2;j++) {
  //fprintf(fout,"%d %d\n",j,(int) *(dat+j));
  //}

  //htdc_frame[ch]->Fill((double)tstamp64/1e8);

  npeaks[ch]=0;
  int nn=0;

  dif[0]=0.0;
  for (j=1;j<n2;j++) {
    dif[j]=*(dat+j) - *(dat+j-1);

    if ( dif[j] >= opt.gam_thresh &&
	      dif[j-1] < opt.gam_thresh) {
      peak64=tstamp64+j;
      if (peak64 > last_peak64[ch]) { //reject double counting

	peaks[ch][nn]=j;

	peaks1[ch][nn]=j+opt.gam_border1;
	peaks0[ch][nn]=j+15;
	peaks2[ch][nn]=j+opt.gam_border2;

	if (peaks1[ch][nn]<0) //too close to the left border
	  peak_flag[ch][nn]=11;
	else if (peaks2[ch][nn]>=n2) //too close to the right border
	  peak_flag[ch][nn]=12;
	else {
	  peak_flag[ch][nn]=2;
	  for (i=nn-1;i>=0;i--) {// this is at least second peak in the sample
	    if (peaks[ch][nn]-peaks[ch][i] < opt.gam_pile1) {
	      //false pileup: only second peak is bad
	      peak_flag[ch][nn]=14;
	    }
	    else if (peaks[ch][nn]-peaks[ch][i] < opt.gam_pile2) { 
	      //real pileup: both peaks are bad
	      peak_flag[ch][nn]=13;
	      peak_flag[ch][i]=13;
	    }
	  }
	}

	last_peak64[ch]=peak64;
	nn++;
	npeaks[ch]=nn;

      } // reject double counting
      //gam_peak(ch,j);
      
    } // if dif...
  } // for j

  //printf("gam2: %d %d\n",ch,npeaks[ch]);

  peakana_gam(ch,n2,dat);

#ifdef ROMASH
  if (npeaks[ch]>0) {
    mult_gam++;
  }
#endif  

}

int deltat(int ng, unsigned int tt) { // fill DeltaT histograms
  int dd=tt-pstop1;

  int num=png1*2+ng;

  if (num>=0 && num < 4) {
    hdeltat[num]->Fill(dd);
  }
  else {
    printf("Wrong ng: %d %d %d\n",num,png1,ng);
  }

  pstop1=tt;
  png1=ng;

  if (dd == 0) {
    printf("DeltaT: %d %d %d %d %d %d %d\n", nevent, num, png1, ng, tt, pstop1, dd);
  }

  return dd;

}

void startbeam(int ch) {
  //Long64_t t_prev;
  if (opt.starts_thr2>0 && ch ==  opt.start_ch &&
      frame_tof2 > opt.starts_thr2) {
    //t_prev = t_ring[nring];
    if (tstamp64 > t_ring[nring]) {
      //cout << "start1: " 
      //<< tstamp64 << " " << t_ring[nring] << endl;
      nring++;
      if (nring>=MAXRING) 
	nring=0;

      if (tstamp64-t_ring[nring] < opt.starts_thr1) {
	//if (t_ring[nring]>0) {
	/*
	cout << "start: " << nevent << " " << start64 << " " 
	     << tstamp64-t_ring[nring] << " "
	     << tstamp64 << " " << t_ring[nring] << " " << tof2 
	     << " " << tof << endl;
	*/
	start64=peak64;
	findbeam=1;
	if (!beam_on) {
	  beam_on=true;
	}
	//return true;
      }
      t_ring[nring]=tstamp64;
    }
  }
  //return false;
}

/*
void fillframe(int ch) {
  htdc_frame[ch]->Fill((double)tstamp64/1e8);
  startbeam(ch);
}
*/

int analyze() //analyze one event
{
  int i,j;

  bool ana_stop=false;

  unsigned int tmp;

  //double bkg1=sdata[0];
  //double max=0.0;
  //int imax=0;
  int it1=0;
  int it2=0;

  //double sum,mean,rms;

  //int bad_rms=0;
  int zero_dt=0;
  //int big_sum=0;

  frame_tof = (tstamp64-first64)*1e-8;
  frame_tof2 = (tstamp64-start64)*1e-8;

  if (frame_tof < opt.Tstart) {
    return 0;
  }
  else if (opt.Tstop && frame_tof > opt.Tstop) {
    //printf("Tstop: %f %f\n",frame_tof,tof);
    //cout << start64 << " " << first64 << " " << tstamp64 << endl;
    return 11;
  }

#ifdef ROMASH
  mult_gam=0;
#endif

  for (i=0;i<mult;i++) {
    int ch = chan[i];
    htdc_frame[ch]->Fill(frame_tof);
    startbeam(ch);

    if (opt.channels[ch]==ch_ng) {
      smooth(opt.nsmoo,i);
      findpeaks_ng(ch,nsamp, sEvent[i]);
    }
    else if (opt.channels[ch]==ch_gam) {
      smooth(opt.nsmoo,i);
      findpeaks_gam(ch,nsamp, sEvent[i]);
    }
    else if (opt.channels[ch]==ch_nim) {
      //htdc_frame[ch]->Fill((double)tstamp64/1e8);
      findpeaks_nim(ch,nsamp, Event[i]);
    }

    //if (ch==8) findbeam=1;

  } //for i

#ifdef ROMASH
  //cout << "MMM: " << mult_gam << " " << frame_tof2 << endl;
  if (mult_gam>0 && mult_gam<24) {
    htof_m[0]->Fill(frame_tof2*1000000);
    htof_m[mult_gam]->Fill(frame_tof2*1000000);
  }
#endif

  //cout << "process" << endl;

  //if (mult>10) {
  //cout << "Mult: " << mult << " Nevent: " << nevent << endl;
  //}

  if (checkpoint) {
    checkpoint=0;
    return 7;
  }

  if (findbeam) {
    findbeam=0;
    return 2;
  }

  //if (big_sum) {
  //return 4;
  //}
  /*
  if (zero_dt>=20 && zero_dt < 50) {
    return 4;
  }
  */
  return 0;

} //analyze

int searchsync() { //returns 0 at the eof; -1 if no syncw was found

  bool bbb;
  int id0=idx;

  do {
    idx+=2;
    if (idx>=r_buf) {
      idx-=r_buf;
      if (readbuf()) {
	return 0;
      }
    }
    bbb = buf[idx+1] == 0x2a50 && (buf[idx]==0x100 || buf[idx]==0x102);
  } while (!bbb);

  //cout << "searchsync idx: " << idx-id0 << endl;
  return idx-id0;

}

void fillevent() {

  for (int i=0;i<nsamp;i+=2) {
    Event[mult][i]=buf[idx+i+11];
    Event[mult][i+1]=buf[idx+i+10];
    //printf("%d %d\n",i,Event[mult][i]);
    //printf("%d %d\n",i+1,Event[mult][i+1]);
  }
  chan[mult]=nch;
  mult++;

}

void fillnewevent() {

  mult=0;

#ifdef LONGSTAMP
  tstamp64 = cnst;
  tstamp64 = tstamp64 << 32;
  tstamp64 += tst;
  tstamp=tst;
  if (!first64) {
    first64=tstamp64;
    cout << "First64: " << tstamp64 << endl;
  }
#else
  pstamp=tstamp;
  tstamp=tst;
  if (double(tstamp) - pstamp < -10000000) {
    //cout << "istamp: " << tstamp << " " << pstamp << " " << 1e9-pstamp << endl;
    if (pstamp < 950000000) 
      {
	cout << "istamp1: " << tof << " " << (1e9-pstamp)*1e-8 << " " 
	     << pstamp << endl;
      }
    if (pstamp > 1005000000) 
      {
	cout << "istamp2: " << tof << " " << (1e9-pstamp)*1e-8 << " " 
	     << pstamp << endl;
      }
    istamp++;
    int iplus=int (opt.tplus*100);
    offset64 = (Long64_t) istamp * 1000000 *(1000+iplus);
    //cout << "offset64: " << offset64 << endl;
  }
  tstamp64 = offset64 + tstamp;
#endif

  fillevent();
}

int nextevent() {//returns 1 if a new event is found; 0 at the end of file.

  //todo:
  // test timestamp
  // test if event/(frame?) length is wrong ??

  //done:
  // what to do at the beginning of the program (first event)
  // what to do at the end of buffer
  // test event id


  //first fill new event
  if (new_event) {
    fillnewevent();
    idx=idnext;
  }
  else {
    new_event=true;
  }

 again:

  //cout << idx << endl;

  type=buf[idx];
  len=buf[idx+3];
  len2=len*2;
  if (len==0x2a50) {
    // short event without length word - > ignore it and go to next one
    printf("Len syncw: %d %d %x\n",len,idx,(recd-r_buf+idx)*2);
    idx+=2;
    if (idx>=r_buf) {
      idx-=r_buf;
      if (readbuf()) {
	//readbuf();
	//if ((r_buf == 0) || feof(fp)) {
	return 0;
      }
    }
    syncw=buf[idx+1];
    goto again;
  }
  else if (len>511) {
    // still bad event... search for new syncw
    printf("Len Error: %d %d %d %x\n",nevent,len,idx,(recd-r_buf+idx)*2);

    //for (int i=idx-100;i<idx+300;i++) {
    //printf("%d %x\n",i,buf[i]);
    //}

    if (!searchsync()) {
      return 0;
    }
    goto again;
  }

  idnext=idx+len2;

  if (idnext>=r_buf) { // at the end of buffer
    //printf("End of buffer: %d %x %d\n",idx,(recd-r_buf+idx)*2,idnext);

    for (int i=idx;i<r_buf;i++) {
      //printf("%d %d %d %d %x\n",idx,r_buf,i,i-r_buf,buf[i]);
      buf[i-r_buf]=buf[i];
    }
    idx-=r_buf;
    idnext-=r_buf;
    if (readbuf()) {
      //readbuf();
      //if ((r_buf == 0) || feof(fp)) {

      printf("eof: %d %d %d\n",idx,idnext,r_buf);

      return 0;
    }

    if (idx < -BOFFSET || idx>=BSIZE) {
      printf("Error: %d %x %d\n",idx,(recd-r_buf+idx)*2,r_buf);
      exit(-1);
    }
    //printf("%d %d %d\n",idx,idnext,r_buf);
    //return 1;
  }

  // here idnext is already guaranteed inside the buffer...

  if (buf[idnext+1]!=0x2a50) { //corrupted event
    //int byte = (recd-r_buf+idx)*2;
    //printf("Corrupted event: %d %x %d %d\n",idx,(recd-r_buf+idx)*2,idnext,len2);

    bad_events++;

    /*
    if (nevent > 6800 && nevent < 6900) {
      for (int i=idx;i<idnext+100;i++) {
	printf("%d %x\n",i,buf[i]);
      }
    }
    */

    //first search for syncw...

    int rr=searchsync();
    if (!rr) {
      return 0;
    }

    if (rr > len2) {
      printf("Corrupted event2: %d %d %x %d %d %d\n",
	     nevent,idx,(recd-r_buf+idx)*2,idnext,rr,len2);

      //for (int i=idx-rr-100;i<idx+100;i++) {
      //printf("%d %x\n",i,buf[i]);
      //}
      
    }

    goto again;

    //for (int i=idx;i<idnext+3;i++) {
    //printf("%d %x\n",i,buf[i]);
    //}

  } //if corrupted event

  if (type == 0x102) { //control block
    //printf("control block %d %d %x\n",nevent,idx,(recd-r_buf+idx)*2);
    idx=idnext;
    goto again;
  }
  else if (type!=0x100) {
    printf("unknown block %d %x %x\n",idx,(recd-r_buf+idx)*2,type);
    idx=idnext;
    goto again;
  }

  // type == 0x100 -> data event

  unsigned int nn = buf[idx+7];
  nn = (nn<<16) + buf[idx+6];
  
  nbits=bits(nn,0,3);
  nw=bits(nn,4,5);
  nsamp=bits(nn,6,17)-1;
  nch=bits(nn,18,25);
  id=bits(nn,26,31);

  if (nch > 31) {
    printf("nch > 31 : %d %x %d %d %d %d\n",id,(recd-r_buf+idx)*2,idx,dlen2,nsamp,nch);
    bad_events++;
    idx=idnext;
    goto again;
  }

  if (id != 0) {
    //dumpbuf();
    printf("id !=0: %d %x %d %d %d %d\n",id,(recd-r_buf+idx)*2,idx,dlen2,nsamp,nch);
    bad_events++;
    idx=idnext;
    goto again;
  }

  if (nsamp!=len2-16) {
    printf("Event length error: %d %d %d %d %d %d\n",nevent,idx,mult,nch,nsamp,len2-16);
    idx=idnext;
    goto again;    
  }
 
  evcnt=buf[idx+8];
  burstcnt=buf[idx+9];

  cnst=(buf[idx+len2-3]<<16)+buf[idx+len2-4];
  tst=(buf[idx+len2-5]<<16)+buf[idx+len2-6];

  //cout << cnst << endl;

#ifdef LONGSTAMP

  //pstamp64=tstamp64;
  //cnst_prev = cnst;

  if (abs(cnst-cnst_prev) >1) {
    if (cnst==0) { //timestamp is reset, but it shouldn't -> end of file
      cout << "Zero tstamp64: " << nevent << " "
	   << cnst << " " << cnst_prev << " " << tst << " " 
	   <<(recd-r_buf+idx)*2 << " " << idnext << " "
	   << r_buf << endl;
      //cout << "Stop" << endl;
      //return 0;
      cnst=cnst_prev;
      idx=idnext;
      goto again;
    }
    if (cnst_prev==0) { //beginning of file; do nothing
    }
    else { //just bad tstamp -> skip event
      cout << "bad tstamp64: " << nevent << " "
	   << cnst << " " << cnst_prev << " " << tst << " " 
	   <<(recd-r_buf+idx)*2 << " " << idnext << " "
	   << r_buf << endl;
      //tstamp64=pstamp64;
      cnst=cnst_prev;
      idx=idnext;
      goto again;
    }
  }
  
  cnst_prev=cnst;

#else
  if (cnst!=1231167506) {
    cout << "bad cnst: " << cnst << endl;
    idx=idnext;
    goto again;
  }    
#endif


  //if (evcnt == evprev) {//this is the part of coincidence
  if (tst==tstamp) {//this is the part of coincidence
    // test for "double" coincidence in the same channel... 
    for (int kk=0;kk<mult;kk++) {
      if (chan[kk]==nch) {
	//printf("Doublecoinc: %d %d %d %d\n",nevent,mult,nch,chan[kk]);
	mult--;
	idx=idnext;
	goto again;
      }
    }
    fillevent();
    idx=idnext;
    goto again;
    //chan[mult]=nch;
    //mult++;
  }
  else { // this is the start of a new event
    ////if (tst==tstamp) {
    ////printf("Missed coincidence: %d %d %d\n",nevent,evcnt,evprev);
    ////}
    //return -> previous event is already recorded; 
    //current event is not yet checked for the coincidence/multiplicity 
    evprev=evcnt;
    nevent++;
    //if (nevent) {
    return 1;
    //}
  }

  printf("Program should never come here: %d %d %d %d %d %d %d\n",
	 idx,len2,nch,evcnt,burstcnt,cnst,tst);

  idx=idnext;
  //type=buf[idx];
  
  return 0;

}

void dumpbuf()
{
  int i;

  //ftmp=fopen("buf.dat","w");
  printf("%x \n",(recd-r_buf+idx)*2);
  for (i=0;i<BSIZE;i++) {
    printf("%d %x %d\n",i,buf[i],buf[i]);
  }
  //close(ftmp);
}

void dumpevent()
{
  int i;

  //ftmp=fopen("event.dat","w");

  //fprintf(ftmp,"%d\n",nevent);
  printf("Event: %d %d %d\n",nevent,dlen2,nsamp);
  for (i=0;i<nsamp;i++) {
    //fprintf(ftmp,"%d %d\n",i,data[i]);
    //printf("%d %d %f\n",i,data[i],sdata[i]);
  }
  //close(ftmp);
}

int readbuf() // 0 if buffer is good; 1 at the end of file
{
  int i;

  /*
  if (recd >= 0) {
    printf("buf: %d events: %d\n",recd,nevent);
    //exit(-1);
  }
  */

  //printf("1 %d\n",fp);
  if (fp) {
    r_buf=fread(buf,sizeof(short),BSIZE,fp);
    //printf("2\n");
  }
  else {
    r_buf=0;
  }

  //if ((r_buf == 0) || feof(fp)) {
  if (r_buf == 0) {
    return 1;
  }
  else {
    //if (new_event) {
    recd+=r_buf;
    //}
    //printf("recd: %d\n",recd);
    return 0;
  }


}

/*
void swap_words(unsigned short* buf, int size)
{
  int i,j;
  unsigned short tmp;
  for (i=0;i<size/2;i++) {
    j=i*2;
    tmp=*(buf+j);
    *(buf+j)=*(buf+j+1);
    *(buf+j+1)=tmp;
  }
}
*/

short int bits(int n, int i1, int i2)
{
  int ll=i2-i1+1;
  unsigned int mask = ((1 << ll)-1);
  //unsigned int mask = (0xFFFF << (32-i2)) >> (32-i2);
  short int r = (n>>i1) & mask;
  //printf("%x %d %d %d %x %d\n",n,i1,i2,ll,mask,r);
  //r = r >> i1;
  return r;
}

void readmonitor(char* fname) {

  char sss[256];
  int dd,mm,yy,h,m,s;
  double mon;

  TDatime tt;
  UInt_t time,time0;

  double xdat[100000];
  double ydat[100000];

  int nn=0;

  TDatime t0 = TDatime(2012,12,1,0,0,0);
  time0=t0.Convert(false);

  ifstream ifs(fname, ifstream::in );

  if (!ifs.good()) {
    cout << "can't open file: " << fname << endl;
    return;
  }
  else {
    while (!ifs.eof()) {
      ifs.getline(sss,256);
      //cout << sss << endl;
      mon=0;
      sscanf(sss,"%d.%d.%d %d:%d:%d %lf",&dd,&mm,&yy,&h,&m,&s,&mon);
      if (yy<100) yy+=2000;
      tt.Set(yy,mm,dd,h,m,s);
      time=tt.Convert(false);
      //printf("%d %d %d %d %d %d %lf %d %d\n",dd,mm,yy,h,m,s,mon,nn,time);
      //tprev=time;
      if (mon>0) {
	//xdat[nn]=(time-time0)/60.0;
	xdat[nn]=time;
	ydat[nn]=mon/1000.0;
	nn++;
      }
    }
  }
  printf("%d\n",nn);
  ifs.close();

  xdat[nn]=xdat[nn-1]+10;

  hmak->SetBins(nn,xdat);
  for (int i=0;i<nn;i++) {
    hmak->SetBinContent(i+1,ydat[i]);
  }

  hmak->GetXaxis()->SetTimeDisplay(1);
  hmak->GetXaxis()->SetTimeOffset(0);

}

void MyMainFrame::exec3event(Int_t event, Int_t x, Int_t y, TObject *selected)
{
   TCanvas *c = (TCanvas *) gTQSender;
   printf("Canvas %s: event=%d, x=%d, y=%d, selected=%s\n", c->GetName(),
          event, x, y, selected->GetName());
   //   printf("Canvas %s: event=%d, x=%d, y=%d \n", c->GetName(),
   //     event, x, y);
}

void MyMainFrame::MakeMonitor() {

  int ch=(int) (opt.vmon[0]+0.5);
  double thr=opt.vmon[1];
  double left=opt.vmon[2];
  double right=opt.vmon[3];
  double deadt=opt.vmon[4];
  double scale=opt.vmon[5];

  /*
  TDatime t0 = TDatime(2012,12,1,0,0,0);
  UInt_t time0=t0.Convert();
  TDatime t1 = TDatime(2012,12,22,23,29,0);
  UInt_t time1=t1.Convert();
  */

  UInt_t time_z = opt.F_start.Convert(false);

#define MAXMON 10000

  double xdat[MAXMON];
  double ydat[MAXMON];

  int nmon=0;

  int nn = htdc_a[ch]->GetNbinsX();

  double last=-999;

  const char* ss = "bar4 SAME";
  fAna = (TCanvas*) gROOT->GetListOfCanvases()->FindObject("Analysis");
  if (fAna==NULL) {
    fAna = new TCanvas("Analysis","Analysis",600,800);
    fAna->Divide(1,2);
    ss="bar4";
    fAna->Connect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)",
		  "MyMainFrame", this,
		  "exec3event(Int_t,Int_t,Int_t,TObject*)");
  }

  fAna->cd(1);

  htdc_a[ch]->Draw();

  gPad->Update();
  double y1=gPad->GetUymin();
  double y2=gPad->GetUymax();

  TLine* ll=new TLine(100,y1,100,y2);
  //ll->SetLineColor(2);
  //ll->DrawClone();
  //TLine::PaintLine(100,y1,100,y2);

  //ll->Delete();

  for (int i=1;i<=nn;i++) {
    double xx=htdc_a[ch]->GetBinCenter(i);
    double yy=htdc_a[ch]->GetBinContent(i);
    if (xx-last >deadt) {
      if (yy>=thr) {

	ll->SetLineColor(2);
	ll->SetX1(xx);
	ll->SetX2(xx);
	ll->DrawClone();

	double x1=xx+left;
	double x2=xx+right;

	/*
	ll->SetLineColor(3);
	ll->SetX1(x1);
	ll->SetX2(x1);
	ll->DrawClone();
	ll->SetX1(x2);
	ll->SetX2(x2);
	ll->DrawClone();
	*/

	int j1=htdc_a[ch]->FindFixBin(x1);
	int j2=htdc_a[ch]->FindFixBin(x2);
	//xdat[nmon]=(xx+time1-time0)/60.0;
	xdat[nmon]=xx+time_z;
	ydat[nmon]=0;
	for (int j=j1;j<=j2;j++) {
	  ydat[nmon]+=htdc_a[ch]->GetBinContent(j);
	}
	ydat[nmon]*=scale;
	nmon++;
	last=xx;
      }
    }
  }

  xdat[nmon]=xdat[nmon-1]+10;

  hmon->SetBins(nmon,xdat);
  for (int i=0;i<nmon;i++) {
    hmon->SetBinContent(i+1,ydat[i]);
  }

  hmon->GetXaxis()->SetTimeDisplay(1);
  hmon->GetXaxis()->SetTimeOffset(0);


  fAna->cd(2);
  hmon->Draw(ss);

  fAna->Update();

}

NumDlg::NumDlg(const TGWindow *p, const TGWindow *main, const char* txt[], 
	       double val[], int nn)
{
  nNum=nn;

  TGLayoutHints *fLay1 = new TGLayoutHints(kLHintsTop | kLHintsRight, 2, 2, 2, 2);

  fMain = new TGTransientFrame(p, main, 10, 10, kHorizontalFrame);
  fMain->Connect("CloseWindow()", "NumDlg", this, "CloseWindow()");
  fMain->DontCallClose(); // to avoid double deletions.

  // use hierarchical cleaning
  fMain->SetCleanup(kDeepCleanup);

  TGVerticalFrame *fFrame1 = new TGVerticalFrame(fMain, 300, 300);
  fMain->AddFrame(fFrame1, fLay1);

   // three buttons are resized up to the parent width.
   // Note! this width should be fixed!
  //double val=199;

  for (int i=0;i<nNum;i++) {
    fHor[i] = new TGHorizontalFrame(fFrame1, 100, 30);
    fFrame1->AddFrame(fHor[i], new TGLayoutHints(kLHintsLeft, 2, 2, 2, 2));
    fLabel[i] = new TGLabel(fHor[i], txt[i]);
    fNum[i] = new TGNumberEntry(fHor[i], val[i], 12, 0);
    fHor[i]->AddFrame(fLabel[i], fLay1);
    fHor[i]->AddFrame(fNum[i], fLay1);
  }

  fHor[nNum] = new TGHorizontalFrame(fFrame1, 100, 30);
  fFrame1->AddFrame(fHor[nNum], new TGLayoutHints(kLHintsCenterX, 2, 2, 2, 2));


  TGTextButton *ok = new TGTextButton(fHor[nNum], "OK");
  ok->Connect("Clicked()", "NumDlg", this, "DoOK()");
  fHor[nNum]->AddFrame(ok, new TGLayoutHints(kLHintsTop,
                                           10, 10, 10, 10));
   

  TGTextButton *cancel = new TGTextButton(fHor[nNum], "Cancel");
  cancel->Connect("Clicked()", "NumDlg", this, "CloseWindow()");
  fHor[nNum]->AddFrame(cancel, new TGLayoutHints(kLHintsTop,
                                               10, 10, 10, 10));
   
   
  fStatusBar = new TGStatusBar(fFrame1, 50, 10, kVerticalFrame);
  //fStatusBar->SetParts(parts, 4);
  //fStatusBar->Draw3DCorner(kFALSE);
  fFrame1->AddFrame(fStatusBar, new TGLayoutHints(kLHintsExpandX, 0, 0, 10, 0));
  fStatusBar->SetText("OK");

  fMain->SetWindowName("");
   
  // gives min/max window size + a step of x,y incrementing 
  // between the given sizes
  fMain->SetWMSizeHints(200, 80, 320, 320, 1, 1);
  fMain->MapSubwindows();
  // important for layout algorithm
  fMain->Resize(fMain->GetDefaultSize());
  fMain->MapWindow();

}

NumDlg::~NumDlg()
{
   fMain->DeleteWindow();
   myM->fNumD=NULL;
}

void NumDlg::CloseWindow()
{

  //int xx,yy;
  //fMain->GetWMPosition(xx,yy);
  //cout << "~NumDLG: " << xx << " " << yy << endl;

  delete this;
   //this=NULL;
}

void NumDlg::DoOK()
{

  char txt[100];
   // Handle ok button.

  //cout << "dook" << endl;

  for (int i=0;i<nNum;i++) {
    opt.vmon[i] = fNum[i]->GetNumber();
    //cout << i << " " << opt.vmon[i] << endl;
  }

  int ch = (int) opt.vmon[0];
  if (ch>=0 && ch<32) {
    if (htdc_a[ch]->Integral()) {
      fMain->SendCloseMessage();
      myM->MakeMonitor();//(int) zz[0]+0.5,zz[1],zz[2],zz[3],zz[4]);
      return;
    }
    else {
      sprintf(txt,"Error: No data for channel %d",ch);
      fStatusBar->SetText(txt);
    }
  }
  else {
    sprintf(txt,"Error: channel %d doesn't exist",ch);
    fStatusBar->SetText(txt);
  }

}

EntryDlg::EntryDlg(const TGWindow *p, const TGWindow *main, const char* title)
{
   // build widgets

  const char* tip1;
  const char* tip2;
  const char* label;

  void *x1,*x2;

  nLine=0;
  nNum=0;

  fMain = new TGTransientFrame(p, main, 10, 10, kHorizontalFrame);
  //fMain = new TGMainFrame(p, 280, 650);
  fMain->Connect("CloseWindow()", "EntryDlg", this, "CloseWindow()");
  fMain->DontCallClose(); // to avoid double deletions.

  // use hierarchical cleaning
  fMain->SetCleanup(kDeepCleanup);

  fCanvas = new TGCanvas(fMain, 280, 620);
  
  fContainer = new TGCompositeFrame(fCanvas->GetViewPort(), 100, 100,
                                     kVerticalFrame);

  fCanvas->SetContainer(fContainer);

  fMain->AddFrame(fCanvas, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY));

  fLay1 = new TGLayoutHints(kLHintsTop | kLHintsCenterX, 2, 2, 2, 2);
  fLay2 = new TGLayoutHints(kLHintsCenterY | kLHintsLeft, 2, 2, 2, 2);
  fLay3 = new TGLayoutHints(kLHintsCenterY | kLHintsLeft, 70, 2, 2, 2);

  /*
  fSetButton = new TGTextButton(fFrame1, "Close", 2);
  fSetButton->Connect("Clicked()", "EntryDlg", this, "DoOK()");
  fFrame1->AddFrame(fSetButton, fLay1);
  */

  TGNumberFormat::EStyle k_int=TGNumberFormat::kNESInteger;
  TGNumberFormat::EStyle k_r1=TGNumberFormat::kNESRealOne;
  TGNumberFormat::EStyle k_r2=TGNumberFormat::kNESRealTwo;
  TGNumberFormat::EStyle k_r3=TGNumberFormat::kNESRealThree;

  TGNumberFormat::EAttribute k_nneg=TGNumberFormat::kNEANonNegative;
  TGNumberFormat::EAttribute k_any=TGNumberFormat::kNEAAnyNumber;

  x1=   NULL;
  tip1= NULL;
  x2=   &opt.gam_thresh;
  tip2= "Differential threshold for gamma channels";
  label="Gam Threshold";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_nneg);

  x1=   &opt.gam_elim1;
  x2=   &opt.gam_elim2;
  tip1= "Low energy limit for gamma histograms";
  tip2= "High energy limit for gamma histograms";
  label="Gam E Limits";
  AddLine3(6,x1,x2,tip1,tip2,label,k_r1,k_nneg);

  x1=   &opt.gam_border1;
  x2=   &opt.gam_border2;
  tip1= "Left border of the peak \n(negative with respect to the threshold crossing)";
  tip2= "Right border of the peak \n(positive with respect to the threshold crossing)";
  label="Gam Peak";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_any);

  x1=   &opt.gam_pile1;
  x2=   &opt.gam_pile2;
  tip1= "Range of false pileups for gamma";
  tip2= "Range of true pileups for gamma";
  label="Gam Pileup";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_nneg);

  x1=   NULL;
  tip1= NULL;
  x2=   &opt.ng_thresh;
  tip2= "Differential threshold for ng channels";
  label="ng Threshold";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_nneg);

  x1=   &opt.ng_elim1;
  x2=   &opt.ng_elim2;
  tip1= "Low energy limit for ng histograms";
  tip2= "High energy limit for ng histograms";
  label="ng E Limits";
  AddLine3(6,x1,x2,tip1,tip2,label,k_r1,k_nneg);

  x1=   &opt.ng_border1;
  x2=   &opt.ng_border2;
  tip1= "Left border of the peak \n(negative with respect to the peak maximum)";
  tip2= "Right border of the peak \n(positive with respect to the peak maximum)";
  label="ng Peak";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_any);

  x1=   NULL;
  tip1= NULL;
  x2=   &opt.ng_pile;
  tip2= "Range of true pileups for ng";
  label="ng Pileup";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_nneg);

  x1=   &opt.nim_thresh1;
  x2=   &opt.nim_thresh2;
  tip1= "Differential threshold for NIM channels";
  tip2= "Width (dead time) of NIM signals";
  label="NIM Threshold";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_nneg);

  x1=   &opt.tdc_bins1;
  x2=   &opt.tdc_bins2;
  tip1= "Bins per second for long_tds";
  tip2= "Bins per second for tds";
  label="TDC Bins";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_nneg);

  x1=   &opt.starts_thr1;
  x2=   &opt.starts_thr2;
  tip1= "Threshold for beam detection";
  tip2= "Minimal interval between beam pulses \n(set it to 0 to use synchro pulses)";
  label="Starts";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_any);

  x1=   &opt.beam1;
  x2=   &opt.beam2;
  tip1= "Left border of the beam (in Time spectra)";
  tip2= "Right border of the beam (in Time spectra) \nif 0 or negative - ignored ";
  label="Beam";
  AddLine3(6,x1,x2,tip1,tip2,label,k_r2,k_any);

  x1=   &opt.wgam1;
  x2=   &opt.wgam2;
  tip1= "";
  tip2= "";
  label="Gamma";
  AddLine3(6,x1,x2,tip1,tip2,label,k_r2,k_nneg);

  x1=   &opt.wneu1;
  x2=   &opt.wneu2;
  tip1= "";
  tip2= "";
  label="Neutrons";
  AddLine3(6,x1,x2,tip1,tip2,label,k_r2,k_nneg);

  x1=   &opt.wtail1;
  x2=   &opt.wtail2;
  tip1= "";
  tip2= "";
  label="Tail";
  AddLine3(6,x1,x2,tip1,tip2,label,k_r2,k_nneg);

  x1=   &opt.start_ch;
  x2=   &opt.psd_ch;
  tip1= "Channel for TOF start signals";
  tip2= "Channel for N-gamma Pulse-Shape-Discrimination";
  label="Start chn;  PSD chn";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_nneg);

  x1=   NULL;
  tip1= NULL;
  x2=   &opt.nsmoo;
  tip2= "Smoothing parameter for gamma and n-gamma signals";
  label="Smooth";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_nneg);

  x1=   NULL;
  tip1= NULL;
  x2=   &opt.tplus;
  tip2= "Time added every 10 sec after each module reset \n(short timestamp version only)";
  label="Tplus";
  AddLine3(6,x1,x2,tip1,tip2,label,k_r2,k_nneg);

  x1=   &opt.Tstart;
  x2=   &opt.Tstop;
  tip1= "Analysis start (sec) in long TDC";
  tip2= "Analysis stop (sec) in long TDC";
  label="T limits";
  AddLine3(6,x1,x2,tip1,tip2,label,k_int,k_nneg);

  x1=   &opt.Ecalibr[0];
  x2=   &opt.Ecalibr[1];
  tip1= "Calibration coefficient A (offset)";
  tip2= "Calibration coefficient B (slope)";
  label="E calibr (A+B*x)";
  AddLine3(6,x1,x2,tip1,tip2,label,k_r3,k_any);

  /*
  fSetButton = new TGTextButton(fFrame1, "Close", 2);
  fSetButton->Connect("Clicked()", "EntryDlg", this, "DoOK()");
  fFrame1->AddFrame(fSetButton, fLay1);
  */

  // set dialog box title
  fMain->SetWindowName(title);
  fMain->SetIconName(title);
  fMain->SetClassHints("NumberEntryDlg", "NumberEntryDlg");
  // resize & move to center
  fMain->MapSubwindows();

  fMain->Resize(fMain->GetDefaultSize());

  /*
  UInt_t width = fMain->GetDefaultWidth();
  UInt_t height = fMain->GetDefaultHeight();
  fMain->Resize(width, height);
  //fMain->Resize(fMain->GetDefaultSize());

  //fMain->CenterOnParent();
  // make the message box non-resizable
  fMain->SetWMSize(width, height);
   
  //fMain->Resize(400, 700);
  //fMain->SetWMSize(400, 700);

  fMain->SetWMSizeHints(width, height, width, height, 0, 0);
  fMain->SetMWMHints(kMWMDecorAll | kMWMDecorResizeH | kMWMDecorMaximize |
		     kMWMDecorMinimize | kMWMDecorMenu,
		     kMWMFuncAll | kMWMFuncResize | kMWMFuncMaximize |
		     kMWMFuncMinimize, kMWMInputModeless);
  */

  fMain->MapWindow();
  fMain->Move(930,0);
  //fMain->SetX(950);

  //gClient->WaitFor(fMain);

   /*
   int* xx, *yy;
   xx = new int;
   yy = new int;
   fMain->GetWMPosition(*xx,*yy);
   cout << "ENTRYDLG: " << *xx << " " << *yy << endl;
   */
}

EntryDlg::~EntryDlg()
{
   // dtor


   fMain->DeleteWindow();
   
   //cout << "~~~ " << myM->fPar << endl;
   //delete myM->fPar;
   myM->fPar=NULL;
   //cout << "~~~ " << myM->fPar << endl;
}

void EntryDlg::AddLine3(int width, void *x1, void *x2, 
			const char* tip1, const char* tip2, const char* label,
			TGNumberFormat::EStyle style, 
			TGNumberFormat::EAttribute attr, 
			int min, int max)
{
  if (nLine>=MXLN) {
    cout << "nLine>=MXLN" << endl;
    return;
  }

  if (nNum+1>=MXNUM) {
    cout << "nNum>=MXNUM" << endl;
    return;
  }

  double zz;

  /*
  if (style==TGNumberFormat::kNESInteger) {
    qq=*((int*) x1);
    //cout << x2 << " " << qq << endl;
    //(int*) x2;
  }
  */

   fHor[nLine] = new TGHorizontalFrame(fContainer, 200, 30);
   fContainer->AddFrame(fHor[nLine], fLay2);

   TGNumberFormat::ELimit limits = TGNumberFormat::kNELNoLimits;
   if (max!=0) {
     limits = TGNumberFormat::kNELLimitMinMax;
   }

   TGLayoutHints* fLay = fLay3;
   if (x1!=NULL) {
     if (style==TGNumberFormat::kNESInteger) {
       zz=*((int*) x1);
     }
     else {
       zz=*((float*) x1);
     }
     fNum[nNum] = new TGNumberEntry(fHor[nLine], zz, width, nNum, style, attr,
				    limits,(double) min,(double) max);
     fNum[nNum]->GetNumberEntry()->SetToolTipText(tip1);
     fNum[nNum]->GetNumberEntry()->Connect("TextChanged(char*)", "EntryDlg", 
					   this, "DoNum3()");
     fHor[nLine]->AddFrame(fNum[nNum], fLay2);
     fLay=fLay2;
     r_entries[nNum]=x1;
     nNum++;
   }

   if (style==TGNumberFormat::kNESInteger) {
     zz=*((int*) x2);
   }
   else {
     zz=*((float*) x2);
   }
   fNum[nNum] = new TGNumberEntry(fHor[nLine], zz, width, nNum, style, attr,
				    limits,(double) min,(double) max);
   fNum[nNum]->GetNumberEntry()->SetToolTipText(tip2);
   fNum[nNum]->GetNumberEntry()->Connect("TextChanged(char*)", "EntryDlg",
					 this, "DoNum3()");
   fHor[nLine]->AddFrame(fNum[nNum], fLay);

   fLabel[nLine] = new TGLabel(fHor[nLine], label);
   fHor[nLine]->AddFrame(fLabel[nLine], fLay2);
   r_entries[nNum]=x2;

   nNum++;

   nLine++;

}
void EntryDlg::CloseWindow()
{

  //int xx,yy;
  //fMain->GetWMPosition(xx,yy);
  //cout << xx << " " << yy << endl;

  //cout << "close" << endl;

  delete this;
   //this=NULL;
}

void EntryDlg::DoNum3()
{

  TGTextEntry *te = (TGTextEntry *) gTQSender;
  Int_t id = te->WidgetId();

  if (id>=0 && id<MXNUM) {
    float xx=fNum[id]->GetNumber();
    //int ix=xx;

    TGNumberFormat::EStyle style= fNum[id]->GetNumStyle();
    if (style==TGNumberFormat::kNESInteger) {
      *((int*)r_entries[id]) = (int) xx;
      //cout << xx << endl;
      //cout << *((int*)r_entries[id]) << endl;
    }
    else {
      *((float*)r_entries[id])=xx;
    }
    //*r_entries[id]=xx;
    /*
    cout << id << " "
	 << xx << " "
	 << opt.gam_thresh << " "
	 << &opt.gam_thresh << " "
	 << r_entries[id] << " "
	 << endl;
    */
    //printf("DoNum3: %d %f %f %f\n",id,xx,opt.Ecalibr[0],opt.Ecalibr[1]);
  }

}

/*
void EntryDlg::DoOK()
{
   // Handle ok button.

  //cout << "dook" << endl;

   fMain->SendCloseMessage();
}
*/

ChanDlg::ChanDlg(const TGWindow *p, const TGWindow *main, const char* title)
{
   // build widgets
   fMain = new TGTransientFrame(p, main, 10, 10, kVerticalFrame);
   fMain->Connect("CloseWindow()", "ChanDlg", this, "CloseWindow()");
   fMain->DontCallClose(); // to avoid double deletions.

   // use hierarchical cleaning
   fMain->SetCleanup(kDeepCleanup);

   fLay1 = new TGLayoutHints(kLHintsCenterY | kLHintsLeft, 0, 0, 0, 0);
   fLay2 = new TGLayoutHints(kLHintsCenterY | kLHintsCenterX, 0, 0, 0, 0);
   fLay3 = new TGLayoutHints(kLHintsCenterY | kLHintsCenterX, 20, 20, 0, 10);
   fLay4 = new TGLayoutHints(kLHintsCenterY | kLHintsLeft, 20, 0, 0, 0);
   //fLay4 = new TGLayoutHints(kLHintsCenterY | kLHintsCenterX, 2, 2, 2, 2);

   fFr1 = new TGHorizontalFrame(fMain, 200, 300);
   fMain->AddFrame(fFr1, fLay1);

   AddColumn(0);
   AddColumn(1);

   int i=MAX_CH;

   //for (int i=MAX_CH; i<MAX_CH+5;i++) {
     fHor[i] = new TGHorizontalFrame(fMain, 100, 30);
     fMain->AddFrame(fHor[i], fLay4);
     FillLast(i,fHor[i]);
     //}

   fFr3 = new TGHorizontalFrame(fMain, 100, 10);
   fMain->AddFrame(fFr3, fLay2);

   TGTextButton* fOK = new TGTextButton(fFr3, " OK ");
   fOK->Connect("Clicked()", "ChanDlg", this, "DoOK()");
   fFr3->AddFrame(fOK, fLay3);

   TGTextButton* fCancel = new TGTextButton(fFr3, " Cancel ");
   fCancel->Connect("Clicked()", "ChanDlg", this, "CloseWindow()");
   fFr3->AddFrame(fCancel, fLay3);

   // set dialog box title
   fMain->SetWindowName(title);
   fMain->SetIconName(title);
   fMain->SetClassHints("NumberEntryDlg", "NumberEntryDlg");
   // resize & move to center
   fMain->MapSubwindows();
   UInt_t width = fMain->GetDefaultWidth();
   UInt_t height = fMain->GetDefaultHeight();
   fMain->Resize(width, height);
   fMain->CenterOnParent();
   // make the message box non-resizable
   fMain->SetWMSize(width, height);
   fMain->SetWMSizeHints(width, height, width, height, 0, 0);
   fMain->SetMWMHints(kMWMDecorAll | kMWMDecorResizeH | kMWMDecorMaximize |
                      kMWMDecorMinimize | kMWMDecorMenu,
                      kMWMFuncAll | kMWMFuncResize | kMWMFuncMaximize |
                      kMWMFuncMinimize, kMWMInputModeless);

   fMain->MapWindow();
   //gClient->WaitFor(fMain);
}

ChanDlg::~ChanDlg()
{
   // dtor

   fMain->DeleteWindow();
   myM->fChan=NULL;
}

void ChanDlg::AddColumn(int i)
{
  fFr2[i] = new TGVerticalFrame(fFr1, 100, 30);
  fFr1->AddFrame(fFr2[i], fLay3);

   //fLabel[0] = new TGLabel(fF[0], "text", myGC(), myfont->GetFontStruct());
  fLabel[i] = new TGLabel(fFr2[i], "ch gam  ng  nim  off         name         color");
  fFr2[i]->AddFrame(fLabel[i], fLay1);

  for (int j=0;j<16;j++) {
    AddLine(i*16+j, fFr2[i]);
  }

}

void ChanDlg::AddLine(int i, TGVerticalFrame *fFr)
{
  //cout << "addline " << i << endl;

  //fHor[i] = new TGGroupFrame(fFr, "",kHorizontalFrame|kRaisedFrame);
  fHor[i] = new TGHorizontalFrame(fFr, 100, 30);
  fFr->AddFrame(fHor[i], fLay1);

  //fFr->AddLine();

  FillLine(i,fHor[i]);

}

void ChanDlg::FillLine(int i, TGHorizontalFrame *fHor)
{

  char txt[10];

  if (i<MAX_CH) {
    sprintf(txt,"%02d  ",i);
  }
  //else if (i<MAX_CH+4) {
  //sprintf(txt,"xxxx%02d  ",i-MAX_CH);
  //}
  else {
    sprintf(txt,"all  ");
  }

  fLab2[i] = new TGLabel(fHor, txt);

  fR[i*MAX_R]   = new TGRadioButton(fHor," ",i*MAX_R);
  fR[i*MAX_R+1] = new TGRadioButton(fHor," ",i*MAX_R+1);
  fR[i*MAX_R+2] = new TGRadioButton(fHor," ",i*MAX_R+2);
  fR[i*MAX_R+3] = new TGRadioButton(fHor," ",i*MAX_R+3);

  fName[i] = new TGTextEntry(fHor, opt.chname[i],i);
  fName[i]->Resize(80, fName[i]->GetDefaultHeight());

  int kk = gROOT->GetColor(opt.color[i])->GetPixel();
  fColor[i] = new TGColorSelect(fHor, kk, i);

  //fLab2[i]->SetBackgroundColor(kk);
  //fR[i*MAX_R+3]->SetBackgroundColor(kk);
  //fR[i*MAX_R+3]->SetForegroundColor(i);

  switch (opt.channels[i]) {
  case ch_gam:
    fR[i*MAX_R]->SetState(kButtonDown);
    fR[i*MAX_R]->ChangeBackground(kk);
    break;
  case ch_ng:
    fR[i*MAX_R+1]->SetState(kButtonDown);
    fR[i*MAX_R+1]->ChangeBackground(kk);
    break;
  case ch_nim:
    fR[i*MAX_R+2]->SetState(kButtonDown);
    fR[i*MAX_R+2]->ChangeBackground(kk);
    break;
  default:
    fR[i*MAX_R+3]->SetState(kButtonDown);
    break;
  };

  fHor->AddFrame(fLab2[i], fLay1);
  fHor->AddFrame(fR[i*MAX_R], fLay1);
  fHor->AddFrame(fR[i*MAX_R+1], fLay1);
  fHor->AddFrame(fR[i*MAX_R+2], fLay1);
  fHor->AddFrame(fR[i*MAX_R+3], fLay1);
  fHor->AddFrame(fName[i],fLay1);
  fHor->AddFrame(fColor[i],fLay1);

  for (int j=0;j<MAX_R;j++) {
    fR[i*MAX_R+j]->Connect("Clicked()", "ChanDlg", this, "DoRadio()");
  }

  fName[i]->Connect("TextChanged(char*)", "ChanDlg", this, "DoSetName()");
  fColor[i]->Connect("ColorSelected(Pixel_t)",
  		     "ChanDlg", this, "DoColor()");
}

void ChanDlg::FillLast(int i, TGHorizontalFrame *fHor)
{

  char txt[10];
  int col;

  sprintf(txt,"all  ");
  fLab2[i] = new TGLabel(fHor, txt);

  fR[i*MAX_R]   = new TGRadioButton(fHor," ",i*MAX_R);
  fR[i*MAX_R+1] = new TGRadioButton(fHor," ",i*MAX_R+1);
  fR[i*MAX_R+2] = new TGRadioButton(fHor," ",i*MAX_R+2);
  fR[i*MAX_R+3] = new TGRadioButton(fHor," ",i*MAX_R+3);

  fName[i] = new TGTextEntry(fHor, opt.chname[i],i);
  fName[i]->Resize(80, fName[i]->GetDefaultHeight());

  col = gROOT->GetColor(opt.color[i])->GetPixel();
  fColor[i] = new TGColorSelect(fHor, col, i);

  switch (opt.channels[i]) {
  case ch_gam:
    fR[i*MAX_R]->SetState(kButtonDown);
    fR[i*MAX_R]->ChangeBackground(col);
    break;
  case ch_ng:
    fR[i*MAX_R+1]->SetState(kButtonDown);
    fR[i*MAX_R+1]->ChangeBackground(col);
    break;
  case ch_nim:
    fR[i*MAX_R+2]->SetState(kButtonDown);
    fR[i*MAX_R+2]->ChangeBackground(col);
    break;
  default:
    fR[i*MAX_R+3]->SetState(kButtonDown);
    break;
  };

  fHor->AddFrame(fLab2[i], fLay1);
  fHor->AddFrame(fR[i*MAX_R], fLay1);
  fHor->AddFrame(fR[i*MAX_R+1], fLay1);
  fHor->AddFrame(fR[i*MAX_R+2], fLay1);
  fHor->AddFrame(fR[i*MAX_R+3], fLay1);
  fHor->AddFrame(fName[i],fLay1);
  fHor->AddFrame(fColor[i],fLay1);

  for (int j=0;j<MAX_R;j++) {
    fR[i*MAX_R+j]->Connect("Clicked()", "ChanDlg", this, "DoRadio()");
  }

  fName[i]->Connect("TextChanged(char*)", "ChanDlg", this, "DoSetName()");
  fColor[i]->Connect("ColorSelected(Pixel_t)",
		     "ChanDlg", this, "DoColor()");
  i++;
  sprintf(txt,"g:");
  fLab2[i] = new TGLabel(fHor, txt);
  col = gROOT->GetColor(opt.color[i])->GetPixel();
  fColor[i] = new TGColorSelect(fHor, col, i);
  fColor[i]->Connect("ColorSelected(Pixel_t)",
		     "ChanDlg", this, "DoColor()");
  fHor->AddFrame(fLab2[i], fLay1);
  fHor->AddFrame(fColor[i],fLay1);

  //cout << i << " " << opt.color[i] << endl;

  i++;
  sprintf(txt,"n:");
  fLab2[i] = new TGLabel(fHor, txt);
  col = gROOT->GetColor(opt.color[i])->GetPixel();
  fColor[i] = new TGColorSelect(fHor, col, i);
  fColor[i]->Connect("ColorSelected(Pixel_t)",
		     "ChanDlg", this, "DoColor()");
  fHor->AddFrame(fLab2[i], fLay1);
  fHor->AddFrame(fColor[i],fLay1);
  i++;
  sprintf(txt,"tail:");
  fLab2[i] = new TGLabel(fHor, txt);
  col = gROOT->GetColor(opt.color[i])->GetPixel();
  fColor[i] = new TGColorSelect(fHor, col, i);
  fColor[i]->Connect("ColorSelected(Pixel_t)",
		     "ChanDlg", this, "DoColor()");
  fHor->AddFrame(fLab2[i], fLay1);
  fHor->AddFrame(fColor[i],fLay1);
  i++;
  sprintf(txt,"unkn:");
  fLab2[i] = new TGLabel(fHor, txt);
  col = gROOT->GetColor(opt.color[i])->GetPixel();
  fColor[i] = new TGColorSelect(fHor, col, i);
  fColor[i]->Connect("ColorSelected(Pixel_t)",
		     "ChanDlg", this, "DoColor()");
  fHor->AddFrame(fLab2[i], fLay1);
  fHor->AddFrame(fColor[i],fLay1);
  i++;
  sprintf(txt,"pileup:");
  fLab2[i] = new TGLabel(fHor, txt);
  col = gROOT->GetColor(opt.color[i])->GetPixel();
  fColor[i] = new TGColorSelect(fHor, col, i);
  fColor[i]->Connect("ColorSelected(Pixel_t)",
		     "ChanDlg", this, "DoColor()");
  fHor->AddFrame(fLab2[i], fLay1);
  fHor->AddFrame(fColor[i],fLay1);

}

void ChanDlg::DoRadio()
{
  int j;

  TGButton *btn = (TGButton *) gTQSender;
  Int_t id = btn->WidgetId();

  int ii=id/MAX_R;
  int k=id%MAX_R;

  Pixel_t bkg=fLabel[0]->GetBackground();

  if (ii>=0 && ii<MAX_CH) {
    for (j=ii*MAX_R;j<ii*MAX_R+MAX_R;j++) {
      if (j!=id) {
	fR[j]->SetState(kButtonUp);
	fR[j]->ChangeBackground(bkg);
      }
    }
    //YK opt.channels[i]=(ChannelDef) k;
    if (k!=MAX_R-1) {
      fR[id]->ChangeBackground(fColor[ii]->GetColor());
      //fR[id]->ChangeBackground(gROOT->GetColor(opt.color[i])->GetPixel());
    }
  }
  else if (ii==MAX_CH) {
    for (int i=0;i<=MAX_CH;i++) {
      for (j=i*MAX_R;j<i*MAX_R+MAX_R;j++) {
	if (j%MAX_R!=k) {
	  fR[j]->SetState(kButtonUp);
	  fR[j]->ChangeBackground(bkg);
	}
	else {
	  fR[j]->SetState(kButtonDown);
	  if (j%MAX_R!=MAX_R-1) {
	    fR[j]->ChangeBackground(fColor[i]->GetColor());
	    //fR[j]->ChangeBackground(gROOT->GetColor(opt.color[i])->GetPixel());
	  }
	}
      }
      //YK opt.channels[i]=(ChannelDef) k;
    }
  }
  else{
    printf("DoRadio: wrong id: %d\n",id);
  }

}

void ChanDlg::DoSetName()
{
  int j;
  char txt[100];


  TGButton *btn = (TGButton *) gTQSender;
  Int_t id = btn->WidgetId();
  if (id>=0 && id<MAX_CH) {
    //strcpy(opt.chname[id],fName[id]->GetText());
  }
  else if (id==MAX_CH) {
    //strcpy(opt.chname[id],fName[id]->GetText());
    for (j=0;j<MAX_CH;j++) {
      if (fR[j*MAX_R+3]->GetState()==kButtonDown) {
	//if (opt.channels[j]==ch_off) {
	sprintf(txt,"%s%02d",fName[id]->GetText(),j);
	fName[j]->SetText(txt);
      }
    }
  }
  else {
    printf("DoSetName: wrong id: %d\n",id);
  }
}

void ChanDlg::DoColor()
{
  int j;

  TGButton *btn = (TGButton *) gTQSender;
  Int_t id = btn->WidgetId();

  //printf("AAA id: %d color: %d\n",id,opt.color[id]);

  if (id>=0 && id<MAX_CH) {
    //opt.color[id]=TColor::GetColor(fColor[id]->GetColor());
  }
  else if (id==MAX_CH) {
    for (j=0;j<MAX_CH;j++) {
      if (fR[j*MAX_R+3]->GetState()==kButtonDown) {
	//if (opt.channels[j]==ch_off) {
	//opt.color[j]=TColor::GetColor(fColor[id]->GetColor());
	fColor[j]->SetColor(fColor[id]->GetColor(),false);
      }
    }
  }
  else if (id<MAX_CH+1+MAX_P) {
    //opt.color[id]=TColor::GetColor(fColor[id]->GetColor());
    // it was already commented!!! fColor[id]->SetColor(fColor[id]->GetColor());
    //printf("xxx id: %d color: %d\n",id,opt.color[id]);
  }
  else {
    printf("DoColor: wrong id: %d\n",id);
  }
}

void ChanDlg::CloseWindow()
{
   delete this;
}

void ChanDlg::DoOK()
{
   // Handle ok button.
  int k;


  for (int i=0;i<=MAX_CH;i++) {
    opt.color[i]=TColor::GetColor(fColor[i]->GetColor());
    strcpy(opt.chname[i],fName[i]->GetText());

    for (int j=i*MAX_R;j<i*MAX_R+MAX_R;j++) {
      if (fR[j]->GetState()==kButtonDown) {
	k=j%MAX_R;
	opt.channels[i]=(ChannelDef) k;
      }
    }
  }

  for (int i=MAX_CH+1;i<MAX_CH+1+MAX_P;i++) {
    opt.color[i]=TColor::GetColor(fColor[i]->GetColor());
  }

  set_hist_attr();

  myM->DoDraw();

   fMain->SendCloseMessage();
}


MyMainFrame::MyMainFrame(const TGWindow *p,UInt_t w,UInt_t h)
	: TGMainFrame(p,w,h) {
  // Create a main frame

  //int nn=2;
  //double xx[nn];
  //double yy[nn];

  bRun = false;

   fMenuBar = new TGMenuBar(this, 35, 50, kHorizontalFrame);

   fMenuFile = new TGPopupMenu(gClient->GetRoot());

   fMenuFile->AddEntry("Read Parameters", M_READINIT);
   fMenuFile->AddEntry("Save Parameters", M_SAVEINIT);
   fMenuFile->AddSeparator();
   fMenuFile->AddEntry("Read ROOT file", M_READROOT);
   fMenuFile->AddEntry("Save ROOT file", M_SAVEROOT);
   fMenuFile->AddSeparator();
   fMenuFile->AddEntry("Browser\tCtrl+B", M_FILE_BROWSE);
   fMenuFile->AddEntry("New Canvas\tCtrl+N", M_FILE_NEWCANVAS);

   //fMenuFile->AddEntry("&Open...", M_FILE_OPEN);
   //fMenuFile->AddEntry("&Save", M_FILE_SAVE);

   fMenuFile->AddSeparator();
   fMenuFile->AddEntry("E&xit", M_FILE_EXIT);

   //fMenuFile->AddPopup("&Cascaded menus", fCascadeMenu);
   fMenuFile->Connect("Activated(Int_t)", "MyMainFrame", this,
                      "HandleMenu(Int_t)");

   fMenuOptions = new TGPopupMenu(gClient->GetRoot());
   fMenuOptions->AddEntry("Channels", M_CHANNELS);
   fMenuOptions->AddEntry("Parameters", M_PARAM);
   fMenuOptions->Connect("Activated(Int_t)", "MyMainFrame", this,
                      "HandleMenu(Int_t)");

   fMenuHist = new TGPopupMenu(gClient->GetRoot());
   fMenuHist->AddEntry("DEMON", M_DEMON);
   fMenuHist->AddEntry("Silicon", M_SI);
   fMenuHist->AddEntry("Silicon - max", M_SIMAX);
   fMenuHist->AddEntry("Energy 1  - 6 ", M_1_6);
   fMenuHist->AddEntry("Energy 7  - 12", M_7_12);
   fMenuHist->AddEntry("Energy 13 - 18", M_13_18);
   fMenuHist->AddEntry("Energy 19 - 24", M_19_24);
   fMenuHist->AddEntry("Energy 25 - 30", M_25_30);
   fMenuHist->AddEntry("Energy 27 - 32", M_27_32);
   fMenuHist->AddEntry("Time 1  - 6 ", M_T1_6);
   fMenuHist->AddEntry("Time 7  - 12", M_T7_12);
   fMenuHist->AddEntry("Time 13 - 18", M_T13_18);
   fMenuHist->AddEntry("Time 19 - 24", M_T19_24);
   fMenuHist->AddEntry("Time 25 - 30", M_T25_30);
   fMenuHist->AddEntry("Time 27 - 32", M_T27_32);
#ifdef ROMASH
   fMenuHist->AddEntry("MTOF 0  - 5 ",  M_TOF0_5  );
   fMenuHist->AddEntry("MTOF 6  - 11",  M_TOF6_11 );
   fMenuHist->AddEntry("MTOF 12  - 17", M_TOF12_17);
   fMenuHist->AddEntry("MTOF 18  - 23", M_TOF18_23);
#endif
   fMenuHist->Connect("Activated(Int_t)", "MyMainFrame", this,
                      "HandleMenu(Int_t)");

   fMenuAna = new TGPopupMenu(gClient->GetRoot());
   fMenuAna->AddEntry("Syncro-pulses histogram", M_SYNC);
   fMenuAna->AddEntry("Make monitor", M_MKMON);
   fMenuAna->AddEntry("Read makankin's monitor", M_MAKAN);
   fMenuAna->Connect("Activated(Int_t)", "MyMainFrame", this,
                      "HandleMenu(Int_t)");

   fMenuHelp = new TGPopupMenu(gClient->GetRoot());
   fMenuHelp->AddEntry("Display Help file", M_HELP);
   //fMenuHelp->AddEntry("Test", M_TEST);
   fMenuHelp->Connect("Activated(Int_t)", "MyMainFrame", this,
                      "HandleMenu(Int_t)");

   fMenuBar->AddPopup("&File", fMenuFile, 
		      new TGLayoutHints(kLHintsTop|kLHintsLeft,0, 4, 0, 0));

   fMenuBar->AddPopup("&Options", fMenuOptions, 
		      new TGLayoutHints(kLHintsTop|kLHintsLeft));

   fMenuBar->AddPopup("Histograms", fMenuHist, 
		      new TGLayoutHints(kLHintsTop|kLHintsLeft));

   fMenuBar->AddPopup("Analysis", fMenuAna, 
		      new TGLayoutHints(kLHintsTop|kLHintsLeft));

   fMenuBar->AddPopup("&Help", fMenuHelp,
		      new TGLayoutHints(kLHintsTop|kLHintsRight));

   AddFrame(fMenuBar, 
	    new TGLayoutHints(kLHintsTop | kLHintsExpandX, 2, 2, 2, 5));

  fcanvas=NULL;
  fAna=NULL;

  fMain = new TGMainFrame(p,w,h);
  // Create canvas widget
  fEcanvas = new TRootEmbeddedCanvas("Pad",this,900,600);
  AddFrame(fEcanvas, new TGLayoutHints(kLHintsExpandX| kLHintsExpandY,
                                              10,10,10,1));

  nPads=0;
  InitCanvas(8);

  /*
  fEcanvas->Clear();
  fEcanvas->GetCanvas()->Divide(3,2);
  TCanvas *fPad = fEcanvas->GetCanvas();
  fPad->SetFillColor(kGray);

  for (int i=1;i<=6;i++) {
    if (opt.b_logy)
      ((TPad*)fPad->GetPad(i))->SetLogy(1);
    else
      ((TPad*)fPad->GetPad(i))->SetLogy(0);
  }

  ((TPad*)fPad->GetPad(2))->SetLogz(1);
  */

  /*
  fPad2 = new TRootEmbeddedCanvas("Pad2",fMain,600,300);
  fMain->AddFrame(fPad2, new TGLayoutHints(kLHintsExpandX| kLHintsExpandY,
                                              10,10,10,1));
  */

  // Create a horizontal frame widget with buttons
  TGHorizontalFrame *hframe = new TGHorizontalFrame(this,10,10);

  TGTextButton *hopen = new TGTextButton(hframe,"Open");
  hopen->Connect("Clicked()","MyMainFrame",this,"DoOpen()");
  hframe->AddFrame(hopen, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGTextButton *hreset = new TGTextButton(hframe,"Reset");
  hreset->Connect("Clicked()","MyMainFrame",this,"DoReset()");
  hframe->AddFrame(hreset, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGTextButton *hclear = new TGTextButton(hframe,"Clear");
  hclear->Connect("Clicked()","MyMainFrame",this,"DoClear()");
  hframe->AddFrame(hclear, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGTextButton *draw = new TGTextButton(hframe,"1 ev");
  draw->Connect("Clicked()","MyMainFrame",this,"Do1event()");
  hframe->AddFrame(draw, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  n_events = new TGNumberEntry(hframe, opt.num_events, 9, 11,
                        TGNumberFormat::kNESInteger,   //style
                        TGNumberFormat::kNEANonNegative,   //input value filter
                        TGNumberFormat::kNELLimitMin, //specify limits
			       0.,0.);                         //limit values

  n_events->Connect("ValueSet(Long_t)", "MyMainFrame", this, "DoSetNum()");
  (n_events->GetNumberEntry())->Connect("TextChanged(char*)", "MyMainFrame", this, "DoSetNum()");

  hframe->AddFrame(n_events, new TGLayoutHints(kLHintsLeft,3,3,2,2));

  TGTextButton *ev_n = new TGTextButton(hframe,"N ev");
  ev_n->Connect("Clicked()","MyMainFrame",this,"DoNevents()");
  hframe->AddFrame(ev_n, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGTextButton *all_ev = new TGTextButton(hframe,"All ev");
  all_ev->Connect("Clicked()","MyMainFrame",this,"DoAllevents()");
  hframe->AddFrame(all_ev, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGTextButton *find_beam = new TGTextButton(hframe,"FBeam");
  find_beam->Connect("Clicked()","MyMainFrame",this,"DoFindBeam()");
  hframe->AddFrame(find_beam, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGTextButton *chk_point = new TGTextButton(hframe,"Chk");
  chk_point->Connect("Clicked()","MyMainFrame",this,"DoChkPoint()");
  hframe->AddFrame(chk_point, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  /*
  TGTextButton *bsave = new TGTextButton(hframe,"Save");
  bsave->Connect("Clicked()","MyMainFrame",this,"DoSave()");
  hframe->AddFrame(bsave, new TGLayoutHints(kLHintsNormal,3,3,2,2));
  */

  TGCheckButton *fcut = new TGCheckButton(hframe, "2Dcut", 11);
  fcut->SetState((EButtonState) opt.b_gcut);
  fcut->Connect("Clicked()","MyMainFrame",this,"DoCheckGcut()");
  hframe->AddFrame(fcut, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGTextButton *cut_g = new TGTextButton(hframe,"Cut_g");
  cut_g->Connect("Clicked()","MyMainFrame",this,"DoGcut(=0)");
  hframe->AddFrame(cut_g, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGTextButton *cut_n = new TGTextButton(hframe,"Cut_n");
  cut_n->Connect("Clicked()","MyMainFrame",this,"DoGcut(=1)");
  hframe->AddFrame(cut_n, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGTextButton *cut_t = new TGTextButton(hframe,"Cut_t");
  cut_t->Connect("Clicked()","MyMainFrame",this,"DoGcut(=2)");
  hframe->AddFrame(cut_t, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGCheckButton *fosc = new TGCheckButton(hframe, "Osc", 11);
  fosc->SetState((EButtonState) opt.b_osc);
  fosc->Connect("Clicked()","MyMainFrame",this,"DoCheckOsc()");
  hframe->AddFrame(fosc, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGCheckButton *fleg = new TGCheckButton(hframe, "Leg", 12);
  fleg->SetState((EButtonState) opt.b_leg);
  fleg->Connect("Clicked()","MyMainFrame",this,"DoCheckLeg()");
  hframe->AddFrame(fleg, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGCheckButton *flogy = new TGCheckButton(hframe, "LogY", 13);
  flogy->SetState((EButtonState) opt.b_logy);
  flogy->Connect("Clicked()","MyMainFrame",this,"DoCheckLogY()");
  hframe->AddFrame(flogy, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGCheckButton *ftime = new TGCheckButton(hframe, "Time", 14);
  ftime->SetState((EButtonState) opt.b_time);
  ftime->Connect("Clicked()","MyMainFrame",this,"DoCheckTime()");
  hframe->AddFrame(ftime, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  TGTextButton *exit = new TGTextButton(hframe,"Stop");
  exit->Connect("Clicked()","MyMainFrame",this,"DoStop()");
  hframe->AddFrame(exit, new TGLayoutHints(kLHintsNormal,3,3,2,2));

  //  AddFrame(fCheckMulti, new TGLayoutHints(kLHintsTop | kLHintsLeft,
  //					  5, 5, 5, 5));
//  fCheckMulti->Connect("Clicked()", "MyMainFrame", this, "HandleButtons()"); 


  AddFrame(hframe, new TGLayoutHints(kLHintsCenterX,2,2,2,2));



  fBar = new TGStatusBar(this, 10, 10);
  Int_t parts[] = {58, 16, 16, 10};
  fBar->SetParts(parts, 4);
  fBar->Draw3DCorner(kFALSE);
  AddFrame(fBar, new TGLayoutHints(kLHintsExpandX,2,2,2,2));

  fBar->SetText(TString("Stop: ")+opt.F_stop.AsSQLString(),2);  
  UpdateStatus();

  /*
  TGHorizontalFrame *hcontr = new TGHorizontalFrame(this);

  Margins *m_thr = new Margins(hcontr, "Thresholds", opt.gam_thresh, 0);
  hcontr->AddFrame(m_thr, new TGLayoutHints(kLHintsExpandX, 0, 0, 2, 2));
  Margins *m_peak = new Margins(hcontr, "Peak", opt.pborder, 0);
  hcontr->AddFrame(m_peak, new TGLayoutHints(kLHintsExpandX, 0, 0, 2, 2));
  Margins *m_delta = new Margins(hcontr, "Delta", opt.pdelta, 0);
  //m_delta->SetToolTipText("This is a text entry widget");
  hcontr->AddFrame(m_delta, new TGLayoutHints(kLHintsExpandX, 0, 0, 2, 2));
  Margins *m_tbins = new Margins(hcontr, "TDC Bins", opt.tdc_bins, 0);
  hcontr->AddFrame(m_tbins, new TGLayoutHints(kLHintsExpandX, 0, 0, 2, 2));
  Margins *m_starts = new Margins(hcontr, "Starts", opt.starts_thr,0);
  hcontr->AddFrame(m_starts, new TGLayoutHints(kLHintsExpandX, 0, 0, 2, 2));
  Margins *m_beam = new Margins(hcontr, "Beam", opt.beam,2);
  hcontr->AddFrame(m_beam, new TGLayoutHints(kLHintsExpandX, 0, 0, 2, 2));
  Margins *m_gamma = new Margins(hcontr, "Gamma", opt.wgam,2);
  hcontr->AddFrame(m_gamma, new TGLayoutHints(kLHintsExpandX, 0, 0, 2, 2));
  Margins *m_neutr = new Margins(hcontr, "Neutrons", opt.wneu,2);
  hcontr->AddFrame(m_neutr, new TGLayoutHints(kLHintsExpandX, 0, 0, 2, 2));
  Margins *m_tail = new Margins(hcontr, "Tail", opt.wtail,2);
  hcontr->AddFrame(m_tail, new TGLayoutHints(kLHintsExpandX, 0, 0, 2, 2));
  */

  //AddFrame(hcontr, new TGLayoutHints(kLHintsCenterX,2,2,2,2));
  // Set a name to the main frame
  SetWindowName(maintitle);
  // Map all subwindows of main frame
  MapSubwindows();
  // Initialize the layout algorithm
  Resize(GetDefaultSize());
  // Map main frame
  MapWindow();

  //MapWindow();

  Move(-100,-100);

  gStyle->SetOptStat(kFALSE);
  gStyle->SetPalette(1,0);

  fPar = new EntryDlg(gClient->GetRoot(), fMain, "Parameters");
  fChan=NULL;
  fNumD=NULL;

  char txt[10];

  //xx[0]=0;
  //yy[0]=0;

  for (int j=0;j<6;j++) {
    fLeg[j] = new TLegend(0.70,0.80,0.99,0.99);
    //sprintf(txt,"dum%d",j);
    //fHist[j] = new TH2F(txt,"",1000,0.,25.,100.,0.,25.);
    //fHist[j]->SetStats(kFALSE);
    //fGr[j] = new TGraph(nn,xx,yy);
    //fHS[j] = new THStack(txt,"");
  }
  //fHS[2]->SetBit(TH1::kCanRebin);

  /*
  fHS[0]->SetTitle("Amplitude");
  fHS[1]->SetTitle("Width_Energy");
  fHS[2]->SetTitle("Long Time");
  fHS[3]->SetTitle("Energy");
  fHS[4]->SetTitle("Width");
  fHS[5]->SetTitle("Time");
  */

}

void MyMainFrame::DoOpen() {

  if (bRun) return;

const char *dnd_types[] = {
   "dat files",     "*.dat",
   "All files",     "*",
    0,               0
};

   static TString dir(".");
   TGFileInfo fi;
   fi.fFileTypes = dnd_types;
   fi.fIniDir    = StrDup(dir);

   //printf("TGFile:\n");

   new TGFileDialog(gClient->GetRoot(), this, kFDOpen, &fi);

   if (fi.fFilename != NULL) {
     //printf("Open file: %s (dir: %s)\n", fi.fFilename, fi.fIniDir);
     //dir = fi.fIniDir;

     strcpy(fname,fi.fFilename);
     printf("TGFile: %s\n",fname);

     strcpy(maintitle,pr_name);
     strcat(maintitle," ");
     strcat(maintitle,fname);

     SetWindowName(maintitle);
     cnst_prev=0;
     newfile();
     fBar->SetText(TString("Stop: ")+opt.F_stop.AsSQLString(),2);  
     UpdateStatus();
     
   }

}

void MyMainFrame::DoRWinit(EFileDialogMode nn) {

  if (bRun) return;

const char *dnd_types[] = {
   "par files",     "*.par",
   "All files",     "*",
    0,               0
};

 char parname[200];

   static TString dir(".");
   TGFileInfo fi;
   fi.fFileTypes = dnd_types;
   fi.fIniDir    = StrDup(dir);

   //printf("TGFile:\n");

   new TGFileDialog(gClient->GetRoot(), this, nn, &fi);

   if (fi.fFilename != NULL) {
     //printf("Open file: %s (dir: %s)\n", fi.fFilename, fi.fIniDir);
     //dir = fi.fIniDir;

     strcpy(parname,fi.fFilename);
     printf("TGFile: %s\n",parname);

     if (nn==kFDOpen) {
       readinit(parname);
       delete fPar;
       fPar = new EntryDlg(gClient->GetRoot(), fMain, "Parameters");
       if (fChan!=NULL) {
	 delete fChan;
	 fChan = new ChanDlg(gClient->GetRoot(), fMain, "Channels");
       }
     }
     else {
       saveinit(parname);
     }
     //newfile();
   }

}

void MyMainFrame::DoReadRoot() {

  if (bRun) return;

const char *dnd_types[] = {
   "par files",     "*.root",
   "All files",     "*",
    0,               0
};

   static TString dir(".");
   TGFileInfo fi;
   fi.fFileTypes = dnd_types;
   fi.fIniDir    = StrDup(dir);

   //printf("TGFile:\n");

   new TGFileDialog(gClient->GetRoot(), this, kFDOpen, &fi);

   if (fi.fFilename != NULL) {

     reset();

     rootname=new char[200];

     strcpy(rootname,fi.fFilename);
     printf("xxxx TGFile: %s\n",rootname);

     readinit(rootname);
     new_hist();
     readroot(rootname);

     nevent=opt.Nevt;
     tof=opt.Tof;

     fBar->SetText(TString("Stop: ")+opt.F_stop.AsSQLString(),2);  
     UpdateStatus();

     if (fPar!=NULL) {
       delete fPar;
       fPar = new EntryDlg(gClient->GetRoot(), fMain, "Parameters");
     }
     if (fChan!=NULL) {
       delete fChan;
       fChan = new ChanDlg(gClient->GetRoot(), fMain, "Channels");
     }

     DoDraw();

   }

}

void MyMainFrame::DoReadMakan() {

  if (bRun) return;

  char fname[200];

  /*
  const char *dnd_types[] = {
    "txt files",     "*.txt",
    "All files",     "*",
    0,               0
  };


  static TString dir(".");
  TGFileInfo fi;
  fi.fFileTypes = dnd_types;
  fi.fIniDir    = StrDup(dir);

  new TGFileDialog(gClient->GetRoot(), this, kFDOpen, &fi);

  if (fi.fFilename == NULL) {
    return;
  }

  strcpy(fname,fi.fFilename);
  */

  strcpy(fname,"/data/nuclotron/2012_12/Monitors/makankin.txt");
  readmonitor(fname);

  const char* ss = "bar4 SAME";

  //cout << "fAna: " << fAna << endl;
  fAna = (TCanvas*) gROOT->GetListOfCanvases()->FindObject("Analysis");
  //cout << "fAna2: " << fAna << endl;

  if (fAna==NULL) {
    fAna = new TCanvas("Analysis","Analysis",600,800);
    //(TCanvas*) gROOT->GetListOfCanvases()->FindObject("cnv");
    fAna->Divide(1,2);
    ss="bar4";
    fAna->Connect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)",
		  "MyMainFrame", this,
		  "exec3event(Int_t,Int_t,Int_t,TObject*)");
  }

  fAna->cd(2);
  hmak->Draw(ss);
  fAna->Update();

}

void MyMainFrame::DoReset() {

  if (bRun) return;

  reset();
  newfile();

  fBar->SetText(TString("Stop: ")+opt.F_stop.AsSQLString(),2);  
  UpdateStatus();
  DoDraw();

}

void MyMainFrame::DoClear() {

  if (bRun) return;

  clear_hist();

  DoDraw();

}

void DrawEvent(int i, int opt_ch, int deriv) {
  double ygr[DSIZE];
  int j;
  char ss[6];

  TLine *lpk[DSIZE];
  TLine *l1[DSIZE];
  //TLine *l0[DSIZE];
  TLine *l2[DSIZE];
  double x1,x2,y1,y2;
  double thresh;

  int k;
  //double min=9999999;

  char label[100];

  int ch=chan[i];

  int flag;


  if (opt_ch==ch_off) {
    //printf("ch_off: %d %d\n",i,chan[i]);
    return;
  }

  /*
  for (j=1;j<npeaks[i]+1;j++) {
    k=peaks[i][j];
    if (sEvent[i][k]<min) {
      min=sEvent[i][k];
    }
  }
  */

  //printf("min: %f\n",min);

  /*
  for (j=0;j<nsamp;j++) {
    ygr[j]=sEvent[i][j];
    //printf("%d %d %f\n",i,j,sEvent[i][j]);
  }
  */

  y1=0.8-npeaks[ch]*0.02;

  TLegend *leg = new TLegend(0.75,y1,0.99,0.99);

  //tp->cd(i);
  //printf("nsamp: %d\n",nsamp);
  TGraph *gr1;

  if (opt_ch==ch_nim) {
    thresh=opt.nim_thresh1;
    if (!deriv) {
      for (j=0;j<nsamp;j++) {
	ygr[j]=Event[i][j]-Event[i][0];
	//ygr[j]=Event[i][j]-BKGR;
      }
    }
    else {
      for (j=1;j<nsamp;j++) {
	ygr[j]=Event[i][j]-Event[i][j-1];
      }
      ygr[0]=0;
    }
  }
  else {
    if (opt_ch==ch_gam)
      thresh=opt.gam_thresh;
    if (opt_ch==ch_ng)
      thresh=opt.ng_thresh;

    if (!deriv) {
      for (j=0;j<nsamp;j++) {
	ygr[j]=sEvent[i][j]-sEvent[i][0];
	//ygr[j]=sEvent[i][j]-BKGR;
      }
    }
    else {
      for (j=1;j<nsamp;j++) {
	ygr[j]=sEvent[i][j]-sEvent[i][j-1];
      }
      ygr[0]=0;
    }
  }

  gr1 = new TGraph (nsamp, xgr, ygr);
  //printf("gr1\n");

  gr1->SetLineColor(1);
  gr1->SetMarkerStyle(20);
  gr1->SetMarkerSize(0.5);
  //gr1->SetFillColor(0);
  //gr1->SetLineWidth(3);
  sprintf(ss,"%d",chan[i]);
  gr1->SetTitle(ss);
  gr1->Draw("ALP");

  //leg->AddEntry(gr1,"Event","l");

  //printf("leg1\n");

  //delete gr1;

  gPad->Update();
  y1=gPad->GetUymin();
  y2=gPad->GetUymax();

  if (deriv) {
    x1=gPad->GetUxmin();
    x2=gPad->GetUxmax();

    TLine* lthr=new TLine(x1,thresh,x2,thresh);
    lthr->SetLineColor(3);
    lthr->Draw();

    TLine* l0=new TLine(x1,0,x2,0);
    l0->SetLineColor(2);
    l0->Draw();

  }

  for (j=0;j<npeaks[ch];j++) {
    flag=peak_flag[ch][j];

    //printf("draw2: %d %d %d %f\n",j,flag,peaks[i][j],rms[i][j]);

    lpk[j] = new TLine(peaks[ch][j],y1,peaks[ch][j],y2);

    if (opt_ch==ch_nim) {
      lpk[j]->SetLineColor(6);
      strcpy(label,"NIM signal");
    }
    else if (opt_ch==ch_ng || opt_ch==ch_gam) {

      l1[j] = new TLine(peaks1[ch][j],y1,peaks1[ch][j],y2);
      //l0[j] = new TLine(peaks0[ch][j],y1,peaks0[ch][j],y2);
      l2[j] = new TLine(peaks2[ch][j],y1,peaks2[ch][j],y2);
      l1[j]->SetLineStyle(2);
      //l0[j]->SetLineStyle(3);
      l2[j]->SetLineStyle(4);

      if (flag==13) {
	lpk[j]->SetLineColor(7);
	sprintf(label,"T pile-up: %d",peaks[chan[i]][j]);
	//strcpy(label,"T pile-up");
      }
      else if (flag==14) {
	lpk[j]->SetLineColor(41);
	sprintf(label,"F pile-up: %d",peaks[chan[i]][j]);
      }
      else if (flag==6) {
	lpk[j]->SetLineColor(6);
	sprintf(label,"NIM signal: %d",peaks[chan[i]][j]);
      }
      else if (flag==2) {
	lpk[j]->SetLineColor(2);
	sprintf(label,"g: %d %0.2f",peaks[chan[i]][j],rms[chan[i]][j]);
      }
      else if (flag==3) {
	lpk[j]->SetLineColor(3);
	sprintf(label,"n: %d %0.2f",peaks[chan[i]][j],rms[chan[i]][j]);
      }
      else if (flag==4) {
	lpk[j]->SetLineColor(4);
	sprintf(label,"t: %d %0.2f",peaks[chan[i]][j],rms[chan[i]][j]);
      }
      else {
	lpk[j]->SetLineColor(8);
	sprintf(label,"unknown: %d %d %0.2f",peaks[chan[i]][j],flag,rms[chan[i]][j]);
      }

      l1[j]->Draw();
      //l0[j]->Draw();
      l2[j]->Draw();

    } // else if opt_ch...

    lpk[j]->Draw();

    leg->AddEntry(lpk[j],label,"l");

  }

  if (opt.b_leg && !deriv) leg->Draw();

}

void MyMainFrame::DoDraw2() {

  int i,mult1;
  //int nx,ny;
  TCanvas* tp_n[6]; 
  char ss[30];

  //printf("fcanvas: %d\n",fcanvas);

  if (opt.b_osc) { 

    //if (fcanvas==NULL) {
    if (gROOT->GetListOfCanvases()->FindObject("tpad")==NULL) {
      fcanvas = new TCanvas("tpad","tpad",300,300);
    }
    else {
      fcanvas->Clear();  
    }

    /*
      m1 nx ny
      1 - 1 1;
      2 - 1 2;
      3 - 2 2;
      4 - 2 2;
      5 - 2 3;
      6 - 2 3;
      789 - 3 3;
    */

    sprintf(ss,"Ev: %ud Tst: %ud",nevent, tstamp);
    //cout << "nevent2: " << nevent << " " << tstamp << endl;
    //sprintf(ss,"Event: %d",nevent);
    fcanvas->SetTitle(ss);

    if (mult >3)
      mult1=3;
    else
      mult1=mult;

    //printf("Draw2: %d\n",mult);

    if (mult1 == 0) {
      printf("Draw2: mult=0\n");
    }
    else {
      fcanvas->Divide(mult1,2);
      //printf("nx,ny: %d %d %d\n",nx,ny,mult1);

      for (i=0;i<mult1;i++) {
	fcanvas->cd(i+1);
	//sprintf(ss,"Pad_%d",i+1);
	//tp_n[i] = (TCanvas*)(fcanvas->GetPrimitive("Pad_1"));
	//printf("Pad: %s %d %d\n",ss,i,tp_n[i]);
	DrawEvent(i,opt.channels[chan[i]],0);
	fcanvas->cd(i+1+mult1);
	DrawEvent(i,opt.channels[chan[i]],1);
      }
    }
    fcanvas->Update();
  }
  else { // !opt.b_osc
    if (fcanvas != NULL) {
      delete fcanvas;
      fcanvas=NULL;
    }
  }


  //TCanvas *fPad = fcanvas;

  //int ny=mult;

}

/*
void MyMainFrame::AddStack(int i, TH1* hh) {

    if (fHS[i]->GetHists()) {
      if (!(fHS[i]->GetHists()->FindObject(hh))) {
	fHS[i]->Add(hh);
      }
    }
    else {
      fHS[i]->Add(hh);
    }

}
*/

void MyMainFrame::InitCanvas(int nn) {

  if (nn!=nPads) {

    //fEcanvas->Clear();
    TCanvas *fPad = fEcanvas->GetCanvas();
    fPad->Clear();

    if (nn==6) {
      fPad->Divide(3,2);
    }
    else if (nn=8) {
      fPad->Divide(4,2);
    }

    fPad->SetFillColor(kGray);
    for (int i=1;i<=nn;i++) {
      ((TPad*)fPad->GetPad(i))->SetFillColor(kWhite);
      if (opt.b_logy)
	((TPad*)fPad->GetPad(i))->SetLogy(1);
      else
	((TPad*)fPad->GetPad(i))->SetLogy(0);
    }

    ((TPad*)fPad->GetPad(2))->SetLogz(1);

    nPads=nn;

  }

}

int getmax(TH1F* hist[]) {

  int j,jmax=-1;
  double max=0;
  double max2;

    for (j=0;j<MAX_CH;j++) {
      if (hist[j]->GetEntries()>0 && opt.channels[j]!=ch_off && 
	  opt.color[j]!=0) {
	max2 = hist[j]->GetMaximum();
	if (max2 > max) {
	  max = max2;
	  jmax=j;
	}
      }
    }

    return jmax;
}

void MyMainFrame::DrawSubPad(int i) {

  int j;
  TBox *b1,*b2,*b3;
  double x1,x2,y1,y2;
  int jmax=0;
  int ng=opt.psd_ch;

  //UInt_t timeoff;

  TCanvas *fPad = fEcanvas->GetCanvas();
  fPad->cd(i);

  switch (i) {

  case 1:

    jmax=getmax(hmax);
    if (jmax<0) break;

    fLeg[i-1]->Clear();
    hmax[jmax]->Draw();
    fLeg[i-1]->AddEntry(hmax[jmax],hmax[jmax]->GetTitle(),"l");

    for (j=0;j<MAX_CH;j++) {
      if (hmax[j]->GetEntries()>0 && opt.channels[j]!=ch_off && 
	  opt.color[j]!=0 && j!=jmax) {
	hmax[j]->Draw("SAME");
	fLeg[i-1]->AddEntry(hmax[j],hmax[j]->GetTitle(),"l");
      }
    }

    if (opt.b_leg) fLeg[i-1]->Draw();

    break;
  case 2:

    gPad->SetLogy(0);
    fLeg[i-1]->Clear();

    hsumrms->Draw("zcol");

    if (opt.b_gcut) {
      for (int ii=0;ii<3;ii++) {
	if (opt.gcut[ii]!=NULL) {	  
	  opt.gcut[ii]->Draw();
	  fLeg[i-1]->AddEntry(opt.gcut[ii],opt.gcut[ii]->GetName(),"l");
	}
      }
    }
    else {
      gPad->Update();
      y2=gPad->PadtoY(gPad->GetUymax());
      b1 = new TBox(opt.wgam1,0.,opt.wgam2,y2);
      b1->SetFillStyle(0);
      b1->SetFillColor(2);
      b1->SetLineColor(2);
      b1->Draw();

      b2 = new TBox(opt.wneu1,0.,opt.wneu2,y2);
      b2->SetFillStyle(0);
      b2->SetFillColor(3);
      b2->SetLineColor(3);
      b2->Draw();

      b3 = new TBox(opt.wtail1,0.,opt.wtail2,y2);
      b3->SetFillStyle(0);
      b3->SetFillColor(4);
      b3->SetLineColor(4);
      b3->Draw();

      fLeg[i-1]->AddEntry(b1,"Gamma","l");
      fLeg[i-1]->AddEntry(b2,"Neutrons","l");
      fLeg[i-1]->AddEntry(b3,"Tail","l");
    }

    if (opt.b_leg) fLeg[i-1]->Draw();

    break;
  case 3:

    jmax=getmax(htdc_a);

    if (jmax<0) break;

    fLeg[i-1]->Clear();
    if (opt.b_time) {
      htdc_a[jmax]->GetXaxis()->SetTimeDisplay(1);
      //timeoff = opt.F_start.Convert(false);
      //htdc_a[jmax]->GetXaxis()->SetTimeOffset(opt.F_start.Convert(true),"gmt");
    }
    else {
      htdc_a[jmax]->GetXaxis()->SetTimeDisplay(0);
    }
    htdc_a[jmax]->Draw();
    fLeg[i-1]->AddEntry(htdc_a[jmax],htdc_a[jmax]->GetTitle(),"l");

    for (j=0;j<MAX_CH;j++) {
      if (htdc_a[j]->GetEntries()>0 && opt.channels[j]!=ch_off && 
	  opt.color[j]!=0 && j!=jmax) {
	htdc_a[j]->Draw("SAME");
	fLeg[i-1]->AddEntry(htdc_a[j],htdc_a[j]->GetTitle(),"l");
      }
    }

    for (j=0;j<MAX_P;j++) {
      if (htdc_a_ng[j]->GetEntries()>0 && opt.color[MAX_CH+j+1]!=0) {
	htdc_a_ng[j]->Draw("SAME");
	fLeg[i-1]->AddEntry(htdc_a_ng[j],htdc_a_ng[j]->GetTitle(),"l");
      }
    }

    if (opt.b_leg) fLeg[i-1]->Draw();
    break;

  case 4:

    hsum[ng]->Draw();
    fLeg[i-1]->Clear();
    fLeg[i-1]->AddEntry(hsum[ng],hsum[ng]->GetTitle(),"l");

    for (j=0;j<MAX_P;j++) {
      if (hsum_ng[j]->GetEntries()>0 && opt.color[MAX_CH+j+1]!=0) {
	hsum_ng[j]->Draw("SAME");
	fLeg[i-1]->AddEntry(hsum_ng[j],hsum_ng[j]->GetTitle(),"l");
      }
    }

    if (opt.b_leg) fLeg[i-1]->Draw();

    break;
  case 5:

    fLeg[i-1]->Clear();

    hrms->Draw();

    fLeg[i-1]->AddEntry(hrms,hrms->GetTitle(),"l");

    //fc_i->Update();

    if (opt.b_gcut) {
      for (j=0;j<MAX_P;j++) {
	if (hrms_ng[j]->GetEntries()>0 && opt.color[MAX_CH+j+1]!=0) {
	  hrms_ng[j]->Draw("same");
	  fLeg[i-1]->AddEntry(hrms_ng[j],hrms_ng[j]->GetTitle(),"l");
	}
      }
    }
    else {//if (!opt.b_gcut) {

      gPad->Update();
      y2=gPad->PadtoY(gPad->GetUymax());

      b1 = new TBox(opt.wgam1,0.,opt.wgam2,y2);
      b1->SetFillStyle(0);
      b1->SetFillColor(2);
      b1->SetLineColor(2);
      b1->Draw();

      b2 = new TBox(opt.wneu1,0.,opt.wneu2,y2);
      b2->SetFillStyle(0);
      b2->SetFillColor(3);
      b2->SetLineColor(3);
      b2->Draw();

      b3 = new TBox(opt.wtail1,0.,opt.wtail2,y2);
      b3->SetFillStyle(0);
      b3->SetFillColor(4);
      b3->SetLineColor(4);
      b3->Draw();

      fLeg[i-1]->AddEntry(b1,"Gamma","f");
      fLeg[i-1]->AddEntry(b2,"Neutrons","f");
      fLeg[i-1]->AddEntry(b3,"Tail","f");

    }
      //}

    if (opt.b_leg) fLeg[i-1]->Draw();

    //fc_i->Update();
    break;
  case 6:

    jmax=getmax(htdc);
    if (jmax<0) break;

    fLeg[i-1]->Clear();
    htdc[jmax]->Draw();
    fLeg[i-1]->AddEntry(htdc[jmax],htdc[jmax]->GetTitle(),"l");

    for (j=0;j<MAX_CH;j++) {
      if (htdc[j]->GetEntries()>0 && opt.channels[j]!=ch_off && 
	  opt.color[j]!=0 && j!=jmax) {
	htdc[j]->Draw("SAME");
	fLeg[i-1]->AddEntry(htdc[j],htdc[j]->GetTitle(),"l");
      }
    }

    for (j=0;j<MAX_P;j++) {
      if (htdc_ng[j]->GetEntries()>0 && opt.color[MAX_CH+j+1]!=0) {
	htdc_ng[j]->Draw("SAME");
	fLeg[i-1]->AddEntry(htdc_ng[j],htdc_ng[j]->GetTitle(),"l");
      }
    }

    if (opt.b_leg) fLeg[i-1]->Draw();
    break;

  default:
    ;
  }

}

void MyMainFrame::Draw_SI() {

  int i;

  //TLine *l1;
  TBox *b1,*b2,*b3;
  double y2;

  double max0,max2;

  TLegend *leg;

  TCanvas *fPad = fEcanvas->GetCanvas();

  InitCanvas(8);

  cout << "SI" << endl;

  for (i=1;i<=8;i++) {
    fPad->cd(i);
    gPad->SetFillColor(kWhite);
    hsum[i]->Draw();
  }

}

void MyMainFrame::Draw_SI_MAX() {

  int i;

  //TLine *l1;
  TBox *b1,*b2,*b3;
  double y2;

  double max0,max2;

  TLegend *leg;

  TCanvas *fPad = fEcanvas->GetCanvas();

  InitCanvas(8);

  cout << "SI" << endl;

  for (i=1;i<=8;i++) {
    fPad->cd(i);
    gPad->SetFillColor(kWhite);
    hmax[i]->Draw();
  }

}

void MyMainFrame::Draw_NAI(int nn) {

  int i;

  //TLine *l1;
  TBox *b1,*b2,*b3;
  double y2;

  double max0,max2;

  TLegend *leg;

  TCanvas *fPad = fEcanvas->GetCanvas();

  InitCanvas(6);

  for (i=1;i<=6;i++) {
    fPad->cd(i);
    gPad->SetFillColor(kWhite);
    hsum[nn+i-1]->Draw();
  }

}

void MyMainFrame::Draw_TNAI(int nn) {

  int i;

  //TLine *l1;
  TBox *b1,*b2,*b3;
  double y2;

  double max0,max2;

  TLegend *leg;

  TCanvas *fPad = fEcanvas->GetCanvas();

  //double tlim=tstamp64/1e8+1;

  InitCanvas(6);

  for (i=0;i<6;i++) {
    fPad->cd(i+1);

    /*
    htdc_a[nn+i]->GetXaxis()->SetRangeUser(0.,tlim);
    htdc_frame[nn+i]->GetXaxis()->SetRangeUser(0.,tlim);
    */

    if (htdc_a[nn+i]->Integral() > htdc_frame[nn+i]->Integral()) {
      htdc_a[nn+i]->Draw();
      htdc_frame[nn+i]->Draw("same");
    }
    else {
      htdc_frame[nn+i]->Draw();
      htdc_a[nn+i]->Draw("same");
    }


    //htdc_frame[nn+i]->Print("base");
    //cout << htdc_frame[nn+i]->GetBinLowEdge(1) << endl;

    fLeg[i]->Clear();
    fLeg[i]->AddEntry(htdc_a[nn+i],htdc_a[nn+i]->GetTitle(),"l");
    fLeg[i]->AddEntry(htdc_frame[nn+i],htdc_frame[nn+i]->GetTitle(),"l");

    if (opt.b_leg) fLeg[i]->Draw();

  }

}

#ifdef ROMASH
void MyMainFrame::Draw_MTOF(int nn) {

  //cout << "MTOF" << endl;

  TCanvas *fPad = fEcanvas->GetCanvas();

  //double tlim=tstamp64/1e8+1;

  InitCanvas(6);

  for (int i=0;i<6;i++) {
    fPad->cd(i+1);
    htof_m[nn+i]->Draw();
  }

}
#endif

void MyMainFrame::DoDraw() {
  int i;

  char ss[180];

  UInt_t time = opt.F_start.Convert(false);
  //cout << "Time: " << time << endl;
  gStyle->SetTimeOffset(time);

  char folder[100],rname[100];
  SplitFilename(string(rootname), folder, rname);

  sprintf(ss,"%s %s Event: %d %s",pr_name,fname,nevent,rname);
  SetWindowName(ss);

  TCanvas *fPad = fEcanvas->GetCanvas();

  switch (opt.draw_opt) {
  case M_DEMON:
    //cout << "aaa" << endl;
    //fPad->Clear();
    InitCanvas(6);
    //cout << "bbb" << endl;
    DrawSubPad(1);
    DrawSubPad(2);
    DrawSubPad(3);
    DrawSubPad(4);
    DrawSubPad(5);
    DrawSubPad(6);
    break;
  case M_SI:
    Draw_SI();
    break;
  case M_SIMAX:
    Draw_SI_MAX();
    break;
  case M_1_6:
    Draw_NAI(0);
    break;
  case M_7_12:
    Draw_NAI(6);
    break;
  case M_13_18:
    Draw_NAI(12);
    break;
  case M_19_24:
    Draw_NAI(18);
    break;
  case M_25_30:
    Draw_NAI(24);
    break;
  case M_27_32:
    Draw_NAI(26);
    break;
  case M_T1_6:
    Draw_TNAI(0);
    break;
  case M_T7_12:
    Draw_TNAI(6);
    break;
  case M_T13_18:
    Draw_TNAI(12);
    break;
  case M_T19_24:
    Draw_TNAI(18);
    break;
  case M_T25_30:
    Draw_TNAI(24);
    break;
  case M_T27_32:
    Draw_TNAI(26);
    break;
#ifdef ROMASH
  case M_TOF0_5:
    Draw_MTOF(0);
    break;
  case M_TOF6_11:
    Draw_MTOF(6);
    break;
  case M_TOF12_17:
    Draw_MTOF(12);
    break;
  case M_TOF18_23:
    Draw_MTOF(18);
    break;
#endif
  default:
    opt.draw_opt=M_DEMON;
    InitCanvas(6);
    DrawSubPad(1);
    DrawSubPad(2);
    DrawSubPad(3);
    DrawSubPad(4);
    DrawSubPad(5);
    DrawSubPad(6);
  }

  fPad->Update();
  //fEcanvas->Update();

  DoDraw2();

}

void MyMainFrame::DoCheckGcut() {
  //printf("CheckDraw\n");
  opt.b_gcut = ! opt.b_gcut;
  DoDraw();
}

void MyMainFrame::DoCheckOsc() {
  //printf("CheckDraw\n");
  opt.b_osc = ! opt.b_osc;
}

void MyMainFrame::DoCheckLeg() {
  //printf("CheckDraw\n");
  opt.b_leg = ! opt.b_leg;
  DoDraw();
}

void MyMainFrame::DoCheckLogY() {
  //printf("CheckDraw\n");
  //for (int jj=0;jj<6;jj++) {
  opt.b_logy = ! opt.b_logy;
  //}

  TCanvas *fPad = fEcanvas->GetCanvas();

  for (int i=1;i<=nPads;i++) {
    if (opt.b_logy) {
      ((TPad*)fPad->GetPad(i))->SetLogy(1);
    }
    else {
      ((TPad*)fPad->GetPad(i))->SetLogy(0);
    }
  }

  DoDraw();
}

void MyMainFrame::DoCheckTime() {
  opt.b_time = ! opt.b_time;
  DoDraw();
}

void allevents() {

  if (!fp || !r_buf) {
    return;
  }

  int ret=0;
  while (nextevent()) {
    if (analyze()==11)
      break;
  }

}

void MyMainFrame::UpdateStatus() {

  char txt[32];
  sprintf(txt,"Evt: %d",nevent);
  fBar->SetText(txt,3);

  UInt_t time = opt.F_stop.Convert(false);
  time -= (UInt_t) tof;
  //cout << "Tof: " << nevent << " " << tof << " " << peak64 << " " << first64 << endl;
  opt.F_start.Set(time);

  fBar->SetText(TString("Start: ")+opt.F_start.AsSQLString(),1);

}

void MyMainFrame::DoAllevents() {

  if (bRun) return;
  bRun=true;

  if (!fp || !r_buf) {
    bRun=false;
    return;
  }

  int ret=0;
  while (nextevent() && bRun) {
    if (analyze()==11)
      break;
    if (! (nevent % 1000)) {
      UpdateStatus();
      gSystem->ProcessEvents();
    }

    if (opt.num_events > 99999) {
      if (nevent % (int) opt.num_events == 0) {
	DoDraw();
      }
    }
  }

  UpdateStatus();

  DoDraw();
  bRun=false;
}

void MyMainFrame::DoFindBeam() {

  if (bRun) return;
  bRun=true;

  if (!fp || !r_buf) {
    //if (!fp) {
    bRun=false;
    return;
  }
  while (nextevent() && bRun) {
    int aaa=analyze();
    if (aaa==11)
      break;
    if (aaa==2) {
      break;
    }
    if (! (nevent % 1000)) {
      UpdateStatus();
      gSystem->ProcessEvents();
    }
  } 

  UpdateStatus();

  DoDraw();
  bRun=false;
}

void MyMainFrame::DoChkPoint() {

  if (bRun) return;
  bRun=true;

  if (!fp || !r_buf) {
    //if (!fp) {
    bRun=false;
    return;
  }
  while (nextevent() && bRun) {
    int aaa=analyze();
    if (aaa==11)
      break;
    if (aaa==7) {
      break;
    }
    if (! (nevent % 1000)) {
      UpdateStatus();
      gSystem->ProcessEvents();
    }
  } 

  UpdateStatus();
  DoDraw();
  bRun=false;
}

void MyMainFrame::Do1event() {
  if (!fp || !r_buf) {
    //if (!fp) {
    return;
  }

  if (nextevent()) {
    analyze();
    DoDraw2();
  }
  UpdateStatus();
}

void MyMainFrame::DoNevents() {
  int i;

  if (bRun) return;
  bRun=true;

  if (!fp || !r_buf) {
    //if (!fp) {
    bRun=false;
    return;
  }

  DoSetNum();

  for (i=0;i<opt.num_events;i++) {
    if (nextevent() && bRun) {
    if (analyze()==11)
      break;
    }
    else
      break;

    if (! (nevent % 1000)) {
      UpdateStatus();
      gSystem->ProcessEvents();
    }

  }

  UpdateStatus();
  //printf("Nevents: %d\n",nevent);
  DoDraw();
  bRun=false;
}

void MyMainFrame::DoSetNum() {

  if (bRun) return;

  opt.num_events=(int) n_events->GetNumber();
  //printf("test %d\n",gg);
}

void MyMainFrame::DoStop() {
  bRun=false;
  DoDraw();
}
void MyMainFrame::DoExit() {
  int i;

  double it[4];

  double sum;

  cout << "DoExit" << endl;

  saveinit("init.par");

  printf("%d bytes\n",recd*2);
  printf("%d events\n",nevent);
  printf("%d bad events\n",bad_events);

  gApplication->Terminate(0);
}

void MyMainFrame::DoSave() {

  if (bRun) return;

  const char *dnd_types[] = {
    "root files",     "*.root",
    0,               0
  };

  int i=0;
  char s_name[100];
  int len;
  int nbins;

  double x,y0,y1,y2,y3,y4,y5;

  char dir[100], name[100], ext[100];
  TGFileInfo fi;

  //string str(fname);
  //string str2 ("c:\\windows\\winhelp.exe");

  SplitFilename (string(fname),dir,name,ext);

  //printf("split: %s %s %s\n",dir,name,ext);
  //SplitFilename (str2);
  //exit(-1);

  strcat(dir,"save/");
  //strcpy(s_name,dir);
  //strcat(s_name,name);
  strcpy(s_name,name);
  strcat(s_name,".root");

  fi.fFileTypes = dnd_types;
  fi.fIniDir    = StrDup(dir);
  fi.fFilename  = StrDup(s_name);

  new TGFileDialog(gClient->GetRoot(), this, kFDSave, &fi);

  if (fi.fFilename == NULL) {
    return;
  }

  saveroot(fi.fFilename);

}

void MyMainFrame::DoGcut(int nn) {
  const char* cname[3] = {"gamma","neutrons","tail"};
  cout << "gcut " << nn << endl;

  TPad *c1 = (TPad*) fEcanvas->GetCanvas()->GetPad(2);
  c1->WaitPrimitive("CUTG","CutG");
  //TCutG *cut1 = new TCutG((TCutG)gPad->GetPrimitive("CUTG"));


  opt.gcut[nn] = new TCutG(*(TCutG*)gROOT->GetListOfSpecials()->FindObject("CUTG"));
  //TCutG *cut2 = new TCutG(*cut1);
  opt.gcut[nn]->SetName(cname[nn]);

  if (nn==0) {
    opt.gcut[nn]->SetLineColor(2);
  }
  else if (nn==1) {
    opt.gcut[nn]->SetLineColor(1);
  }
  else if (nn==2) {
    opt.gcut[nn]->SetLineColor(4);
  }
  c1->cd();
  opt.gcut[nn]->Print();
  opt.gcut[nn]->Draw();

  //TCutG *cut1 = new TCutG( (TCutG) gPad->GetPrimitive("CUTG"));
  //TCutG* cut = (TCutG*)gPad->GetPrimitive("CUTG");

}


void MyMainFrame::DoSync() {

  TCanvas* cnv = (TCanvas*) gROOT->GetListOfCanvases()->FindObject("cnv");

  if (cnv!=NULL) {
    delete cnv;
  }

  cnv = new TCanvas("cnv","cnv",600,400);  

  hsync->Draw();

}

void MyMainFrame::DoInitMON() {

  if (bRun) return;

    const char* numtxt[] = {
      "Monitor channel number:",
      "Threshold:",
      "Left border in sec (negative):",
      "Right border in sec (positive):",
      "Dead time in sec",
      "Scale factor"
    };
    /*
    double numval[] = {
      8,
      10,
      -0.1,
      0.6,
      6
    };
    */
    fNumD = new NumDlg(gClient->GetRoot(), fMain, numtxt, opt.vmon ,6);
}


//______________________________________________________________________________

/*
void MyMainFrame::HandleHelp()
{

  if (bRun) return;

  cout << "test" << endl;

       char command[128];

       strcpy(command,"evince ");
       strcat(command,"help.pdf");
       int status = system( command );

       cout << status << endl;

}
*/
//______________________________________________________________________________
void MyMainFrame::HandleMenu(MENU_COM menu_id)
{

  char command[128];
  int status;

  if (bRun) return;

  //cout << menu_id << endl;

   // Handle menu events.

   // TRootHelpDialog *hd;
   // static TString dir(".");
   // TGFileInfo fi;
   // fi.fFileTypes = dnd_types;
   // fi.fIniDir    = StrDup(dir);

  switch (menu_id) {

  case M_READINIT:
    DoRWinit(kFDOpen);
    break;
  case M_SAVEINIT:
    DoRWinit(kFDSave);
    break;
  case M_SAVEROOT:
    DoSave();
    break;
  case M_READROOT:
    DoReadRoot();
    break;
  case M_FILE_BROWSE:
    new TBrowser();
    break;
  case M_FILE_NEWCANVAS:
    gROOT->MakeDefCanvas();
    break;

  case M_PARAM:
    if (fPar!=NULL) {
      delete fPar;
    }
    fPar = new EntryDlg(gClient->GetRoot(), fMain, "Parameters");
    break;

  case M_CHANNELS:
    if (fChan!=NULL) {
      delete fChan;
    }
    fChan = new ChanDlg(gClient->GetRoot(), fMain, "Channels");
    break;

  case M_DEMON:
  case M_SI:
  case M_SIMAX:
  case M_1_6:
  case M_7_12:
  case M_13_18:
  case M_19_24:
  case M_25_30:
  case M_27_32:
  case M_T1_6:
  case M_T7_12:
  case M_T13_18:
  case M_T19_24:
  case M_T25_30:
  case M_T27_32:
#ifdef ROMASH
  case M_TOF0_5:
  case M_TOF6_11:
  case M_TOF12_17:
  case M_TOF18_23:
#endif
    opt.draw_opt=menu_id;
    DoDraw();
    break;

  case M_SYNC:
    DoSync();
    break;

  case M_MKMON:
    if (fNumD!=NULL) {
      delete fNumD;
    }
    DoInitMON();
    break;

  case M_MAKAN:

    DoReadMakan();

    break;

  case M_HELP:

    strcpy(command,"sevince ");
    strcat(command,"help.pdf &");
    status = system( command );

    //cout << status << endl;

    break;

  case M_TEST:

    //new TestDirList(gClient->GetRoot(), fMain, 400, 200);

    break;

  case M_FILE_EXIT:
    DoExit();   // terminate theApp no need to use SendCloseMessage()
    break;
  }
}

MyMainFrame::~MyMainFrame() {
  // Clean up used widgets: frames, buttons, layouthints
  //printf("end\n");
  Cleanup();
  //DoExit();
  //delete fMain;
  gApplication->Terminate(0);
}


void example() {
  // Popup the GUI...
  myM = new MyMainFrame(gClient->GetRoot(),800,600);
  //myM->Move(-100,-100);
}

